Python 2.3.3 super() behaviour

Nicolas Lehuen nicolas.lehuen at thecrmcompany.com
Wed Apr 21 06:01:21 EDT 2004


OK, I get it now, thanks.

super() method calls should only be used for method involved in
diamond-shaped inheritance. This is logical since in this case the base
classe (from which the diamond-shaped inheritance starts) defines the
interface of the method.

This solves another question I was asking myself about super() : "how can it
work when the method signature differ between B and C ?". Answer : the
method signature should not change because polymorphic calls would be
greatly endangered. The base class defines the signature of the method which
must be followed by all its children, this way super() can work properly.

The base method signature is not enforced by Python, of course, but you'd
better respect it unless you get weird result in polymorphic calls.

Regards,
Nicolas

"Peter Otten" <__peter__ at web.de> a écrit dans le message de
news:c65fbo$1q4$05$1 at news.t-online.com...
> Nicolas Lehuen wrote:
>
> > Hi,
> >
> > I hope this is not a FAQ, but I have trouble understanding the behaviour
> > of the super() built-in function. I've read the excellent book 'Python
in
> > a Nutshell' which explains this built-in function on pages 89-90. Based
on
> > the example on page 90, I wrote this test code :
> >
> > class A(object):
> >     def test(self):
> >         print 'A'
> >
> > class B(object):
> >     def test(self):
> >         print 'B'
> >
> > class C(A,B):
> >     def test(self):
> >         super(C,self).test()
> >         print 'C'
> >
> > print C.__mro__
> > c=C()
> > c.test()
> >
> > The output is :
> > (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type
> > 'object'>)
> > A
> > C
> >
> > Whereas I was expecting :
> > (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type
> > 'object'>)
> > A
> > B
> > C
> >
> > Was I wrong to expect this (based on what I've read ?)
>
> As soon as a test() method without the super(...).test() is reached, no
> further test methods will be invoked. Only the first in the list of base
> classes will be invoked. If I'm getting it right you have to do something
> like:
>
> class Base(object):
>     def test(self):
>         print "base"
>
> class D1(Base):
>     def test(self):
>         super(D1, self).test()
>         print "derived 1"
>
> class D2(Base):
>     def test(self):
>         super(D2, self).test()
>         print "derived 2"
>
> class All(D1, D2):
>     pass
>
> All().test()
>
> Here all cooperating methods have a super() call, and the base class acts
as
> a showstopper to prevent that Python tries to invoke the non-existent
> object.test().
>
> Peter
>
>
>





More information about the Python-list mailing list