a "generic" problem

Manuel Garcia news at manuelmgarcia.com
Thu Feb 13 00:34:54 CET 2003


Please forgive, I didn't have time to read all the details in your
post, but I remember having a similar problem, so maybe this will
help...

(also I like to run code before I post, and in this case I haven't)
:-/

On Wed, 12 Feb 2003 15:46:06 -0500, "Sean Ross"
<frobozz_electric at hotmail.com> wrote:
(edit)
>        #
>        # create new instances c1, c2 of whichever class p1, p2 belong to
>        #

If you can get away with just copying p1 & p1, then:

    import copy

    c1 = copy.copy(p1)
    c2 = copy.copy(p2)

Otherwise...

Every instance has the attribute __class__.  Call this to run the
class's constructor:

    c1 = p1.__class__()
    c2 = p2.__class__()

>ISSUE 2:
>"How do I implement this method, so that I do not need to
>override it for each sublass?"

instead of using 'staticmethod', use 'classmethod'

'staticmethod' works like this:

    class fake1():
        def meth1(x,y,z):
            print 'static %r' % (x+y+z,)
            return 17
        meth1 = staticmethod(meth1)

'classmethod' works like this:

    class fake2():
        def meth2(cls, x,y,z):
            print '%s %r' % (cls.__name__, x+y+z)
            return cls(x+y+z)
        meth2 = classmethod(meth2)

My example doesn't make sense, but I hope you see the syntax
structure.  Via the variable 'cls', you have access to the class
involved with method f.  Both of these work, for staticmethod and
classmethod:

    fake.meth(x,y,z)

    a = fake()
    a.meth(x,y,z)

What I am trying to say is that you don't even have to have an
instance to use a staticmethod or a classmethod, you can just run the
method from the class directly.

>ISSUE 3:
>   "Is there a way to overide the value of a class variable of the super
>class
>    inside the inheriting class?"

Is this what you mean?

    class fake3():
        attr1 = 17
        attr2 = 19

    class subfake1(fake3): pass

    class subfake2(fake3):
        attr2 = 23

No special steps to override!  I may be misunderstanding you.

Hope this helps!

Manuel




More information about the Python-list mailing list