[Tutor] OO newbie

Kent Johnson kent37 at tds.net
Fri Apr 8 14:08:49 CEST 2005


Alan Gauld wrote:
>>this exemple will also works if you replace the:
>>super(C,self).__init__( *args, **kw)
>>by
>>dict.__init__(self, *args, **kw)
>>
>>but I do not understand this dict.__init_... call.
>>Shouldn't you call the super class constructor??
> 
> 
> super is just a convenience feature added to make Python slightly
> more like some other OOP languages. It is effectively just a
> wrapper around the explicit call to the super class:
> 
> Thus super(C,self...) is the same as
> 
> dict.__init__(self...)


No, super() is much smarter than that and was created to address deficiencies in direct superclass 
calling. super(C, self) actually finds the class that follows C in the method resolution order of 
the class of self. This can be very different from just calling the base class method; in the case 
of multiple inheritance super(C, self) may not ever refer to a base class of C.

For example this program:

class A(object):
     def __init__(self, *args, **kwds):
         print 'A.__init__()'
         super(A, self).__init__(*args, **kwds)

class B(object):
     def __init__(self, *args, **kwds):
         print 'B.__init__()'
         super(B, self).__init__(*args, **kwds)

class C(A, B):
     def __init__(self, *args, **kwds):
         print 'C.__init__()'
         super(C, self).__init__(*args, **kwds)
C()

prints:
C.__init__()
A.__init__()
B.__init__()


For the original question (class SuperDict(dict,A)) this will not help because dict doesn't seem to 
call super(dict, self).__init__(). But if dict is listed as the last base class it works:

class mydict(A, dict):
     def __init__(self, *args, **kwds):
         print 'mydict.__init__()'
         super(mydict, self).__init__(*args, **kwds)

d=mydict(a=1, b=2)
print d

prints:
mydict.__init__()
A.__init__()
{'a': 1, 'b': 2}

so you can see both A.__init__() and dict.__init__() have been called.

For a fairly clear explanation see http://www.python.org/2.2/descrintro.html#cooperation

Kent



More information about the Tutor mailing list