super() and automatic method combination

Laszlo Zsolt Nagy gandalf at geochemsource.com
Wed May 18 12:21:41 EDT 2005


>Which is fine so long as nobody else tries to add further subclasses later:
>
>class C(B): ...
>class Mine(AB,C): ...
>
>Mine().f()
>
>Using super throughout this works (it calls f in Mine, AB, A, C, B, and 
>then Base), but your explicit call to the base classes means that if you 
>don't call C.f() explicitly from Mine it never gets called, and if you do 
>call it explicitly from Mine it gets called *after* B.f() has been called 
>(and B.f() probably ends up being called twice).
>  
>
Okay, I understand now. It was a good learning session for me. :-)
At this moment I do not see a problem where I would need a diamond 
shaped inheritance graph but
I'll keep in mind the difference between super and direct calls. :-)

I tested this and I realized that if you change the parameter list in 
the descendants then it is not wise to use super.
I'm going to publish the example below, I hope others can learn from it too.

Example (good):

class A(object):
    def f(self):
        print "A.f called"
       
class B(A):       
    def f(self):
        super(B,self).f()
        print "B.f called"
       
class C(A):       
    def f(self):
        super(C,self).f()
        print "C.f called"       
       
class D(B,C):       
    def f(self):
        super(D,self).f()
        print "D.f called"               
       
       
d = D()
d.f()

Results in:

A.f called
C.f called
B.f called
D.f called

Example (bad):

class B(A):       
    def f(self,what):
        super(B,self).f()
        print "B.f called (%s)" % what

Will result in:

C:/Python24/pythonw.exe -u  "C:/Python/Projects/Test4/test4.py"
Traceback (most recent call last):
  File "C:/Python/Projects/Test4/test4.py", line 22, in ?
    d.f()
  File "C:/Python/Projects/Test4/test4.py", line 17, in f
    super(D,self).f()
TypeError: f() takes exactly 2 arguments (1 given)

Of course you cannot tell if super(C,self).f() will call A.f or not 
(when add another
subclass under class A, it will change the MRO...)

If you do not want to add any other subclasses then probably you can use

super(C,self).f('foo')

but in that case it is equivalent to

A.f(self,'foo')

Best,

   Laci 2.0



-- 
_________________________________________________________________
  Laszlo Nagy		      web: http://designasign.biz
  IT Consultant		      mail: gandalf at geochemsource.com

     		Python forever!





More information about the Python-list mailing list