Creating new types and invoking super

Guilherme Polo ggpolo at gmail.com
Wed Jan 23 19:11:15 EST 2008


2008/1/23, Arnaud Delobelle <arnodel at googlemail.com>:
> 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
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks for this concept, works better than mine :)


-- 
-- Guilherme H. Polo Goncalves



More information about the Python-list mailing list