Creating new types and invoking super

Arnaud Delobelle arnodel at googlemail.com
Wed Jan 23 18:51:10 EST 2008


On Jan 23, 10:18 pm, "Guilherme Polo" <ggp... at gmail.com> wrote:
> 2008/1/23, Arnaud Delobelle <arno... at googlemail.com>:
>
> > The only way I can think of would be to create a metaclass, but I
> > don't think it's worth it.  super(A, obj).__init__() isn't that bad!
>
> Metaclass doesn't apply here because metaclass is related to
> class-construction. This is related to instance initialization, and
> I'm creating the types as the user asks.

Not completely clear to me what you want but here is a 'proof of
concept':

==========

class callsuper(object):
    def __init__(self, f):
        self.f = f
    def __get__(self, obj, cls=None):
        def newfunc(*args, **kwargs):
            super(self.cls, obj).__init__()
            return self.f(obj, *args, **kwargs)
        return newfunc

class Type(type):
    def __init__(self, name, bases, attrs):
        for attrname, attr in attrs.iteritems():
            if isinstance(attr, callsuper):
                attr.cls = self

class A:
    __metaclass__ = Type
    def __init__(self):
        print "init A"

class B(A):
    @callsuper
    def __init__(self):
        print "init B"

==========

>>> b=B()
init A
init B




More information about the Python-list mailing list