Python 2.3.3 super() behaviour
Peter Otten
__peter__ at web.de
Wed Apr 21 14:54:49 EDT 2004
Josef Meile wrote:
> Peter Otten wrote:
> > 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()
> Ok, this produces almost what the original poster wanted. You
> just have to invert the order of the base classes in All:
>
> >>>class All(D2, D1):
> ... pass
> ...
>
> then you will get:
> >>> All().test()
> base
> derived 1
> derived 2
>
> However, I don't understand jet why this doesn't print:
>
> base
> derived 1
> base
> derived 2
>
> The method test of Base is called just once? Why?
> I taught it was something like:
>
> All.test() -> D1.test() + D2.test()
>
> which is the same as:
>
> (Base.test() + print "derived 1") + (Base.test() + print derived 2")
>
> Thanks in advanced,
> Josef
Every instance has just one __dict__, so calling the same Base method twice
would at best be redundant. The Python designers are a bit smarter than
that and implemented "cooperative" methods for newstyle classes. See
http://www.python.org/2.2/descrintro.html#cooperation for the details.
Peter
More information about the Python-list
mailing list