trouble understanding super()

Simon Forman rogue_pedro at yahoo.com
Mon Jul 31 12:30:50 EDT 2006


John Salerno wrote:
> Here's some code from Python in a Nutshell. The comments are lines from
> a previous example that the calls to super replace in the new example:
>
> class A(object):
>      def met(self):
>          print 'A.met'
>
> class B(A):
>      def met(self):
>          print 'B.met'
>          # A.met(self)
>          super(B, self).met()
>
> class C(A):
>      def met(self):
>          print 'C.met'
>          # A.met(self)
>          super(C, self).met()
>
> class D(B, C):
>      def met(self):
>          print 'D.met'
>          # B.met()
>          # C.met()
>          super(D, self).met()
>
> Then you call D().met()
>
> Now, I understand that the commented code would cause A.met to be called
> twice. But why does the second version (with super) not also do this? I
> guess my problem lies in not understanding exactly what the super
> function returns.
>
> super(D, self).met() seems like it would return something that has to do
> with both B and C, which each in turn return a superobject having to do
> with A, so why isn't A.met called twice still?
>
> Thanks!


Basically super(class_, self).method  looks in self's mro (it's list of
base classes) for class class_, and then starts searching *after* class
class_ for the next class that implements the method.

In this case the object's (instance of D) mro will be (D, B, C, A,
object), so as super gets called in each class, it looks in that list
(tuple, whatever) for the class following it (actually the next class
following it that implements the method).

Since no class appears in that list more than once, each class's
implementation of the method will only be called once.


HTH,
~Simon


Also, if you haven't already, read:
http://www.python.org/download/releases/2.2.3/descrintro/#cooperation




More information about the Python-list mailing list