calling super()

John Clark clajo04 at mac.com
Wed Apr 4 22:25:37 CEST 2007


Please be aware that super() has it's own set of gotchas - it's not as clean
as you would hope.  For more info: http://fuhm.org/super-harmful/

(I'm not the author, I was referred to this article while struggling with
wxPython and super())

-John Clark 

-----Original Message-----
From: python-list-bounces+clajo04=mac.com at python.org
[mailto:python-list-bounces+clajo04=mac.com at python.org] On Behalf Of Laszlo
Nagy
Sent: Wednesday, April 04, 2007 4:09 PM
To: Jarek Zgoda; python-list at python.org; Finger.Octopus at gmail.com
Subject: Re: calling super()

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


--
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list