using super

Michele Simionato michele.simionato at gmail.com
Tue Jan 1 02:59:20 EST 2008


On Jan 1, 7:56 am, iu2 <isra... at elbit.co.il> wrote:
> no one has to remember to call the parent's get_name method. It's done
> automatically.
>
> (A PEP maybe? I sense you don't really like it.. ;-)
> What do you think? Good? Too implicit?
>
> iu2

No PEP, this would never pass. There would be no way
to stop a method from calling its parent: you would
lose control of your classes, so I think this is a
bad idea. Having said so, it is easy to implement
what you want with a metaclass:

def callParent(*methodnames):
     class Meta(type):
         def __init__(cls, name, bases, dic):
             for methodname in methodnames:
                 if methodname in dic:
                     def new_meth(self, method=methodname):
                         parent = getattr(super(cls, self), method,
None)
                         if parent: parent()
                         child = dic.get(method)
                        if child: child(self)
                     setattr(cls, methodname, new_meth)
     return Meta

class B(object):
    __metaclass__ = callParent('get_name')
    def get_name(self):
        print "This is B.get_name"

class C(B):
    def get_name(self):
        print "This is C.get_name"


C().get_name()


Now every subclass of B defining a get_name method
will automagically call its parent method.

   Michele Simionato



More information about the Python-list mailing list