Inheriting from object
Peter Hansen
peter at engcorp.com
Sat Jul 2 14:17:32 EDT 2005
Bengt Richter wrote:
> BTW, there's something about referring to type(self) by its not
> always dependably bound (though usually global) name that bothers me.
>
> I wonder if the above common use of super could be implemented as a property of object,
> so you'd normally inherit it and be able to write
> self.super.__init__(*args, **kwargs) # (maybe spell it self.__super__.__init__(...) I suppose)
>
> I.e., self.__super__ would effectively return the equivalent of
> super(type(self), self)
This doesn't work: type(self) is always the type of the instantiated
(child) class, not the type of the class at whatever level of the class
hierarchy the __init__() calls currently have reached.
In other words, with these definitions:
class A(object):
def __init__(self):
super(type(self), self).__init__() # does not do what you want
class B(A):
def __init__(self):
super(type(self), self).__init__() # works okay here
if you do "b = B()", the first __init__ will work (i.e. B's __init__
will find and call A.__init__), but the next one won't (i.e. A.__init__
will now try calling A.__init__ recursively, giving you an eventual
stack overflow).
-correcting-bengt-richter-on-such-arcana-is-always-dangerously y'rs,
Peter
More information about the Python-list
mailing list