calling super()
Laszlo Nagy
gandalf at designaproduct.biz
Wed Apr 4 16:08:57 EDT 2007
Jarek Zgoda wrote:
>> Hello, I have been trying to call the super constructor from my
>> derived class but its not working as expected. See the code:
>>
>> class HTMLMain:
>> def __init__(self):
>> self.text = "<HTML><BODY>";
>> print(self.text);
>> def __del__(self):
>> self.text = "</BODY></HTML>";
>> print(self.text);
>>
>> class NewPage(HTMLMain):
>> def __init__(self):
>> print 'derive2 init'
>> super(NewPage, self).__init__();
>>
>
> This should read: super(HTMLMain, self).__init__()
>
Definitely, this is not true. Well, it depends what the OP wanted to do
here, but in 99.9% of the cases, you want to use
class B(A):
def method(self,*args):
super(B,self).method(*args)
Look at here: http://www.python.org/doc/2.3.5/lib/built-in-funcs.html#l2h-66
It tells that super(type,[self]) will """Return the superclass of
type.""". So super(B) will return the superclass of B, that is A. The
built-in function "super" is very useful when you have diamond-shaped
inheritance and you only want each inherited method to be called only
once, IN THE CORRECT ORDER. If you only have single inheritance class
trees, then super(B,self).method(*args) is identical to
A.method(self,*args). You only need to worry about method calling order
when you use multiple inheritance. However, using super is much nicer
than calling the method of the base class directly, and it is
syntactically cleaner, since you will only have a single reference to
the base class, in the class definition header. (E.g. you can change the
base class by replacing one word in the source code...)
Best,
Laszlo
More information about the Python-list
mailing list