Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

Raymond Hettinger python at rcn.com
Sun Jul 25 13:02:52 EDT 2010


On Jul 24, 3:56 am, Lacrima <lacrima.ma... at gmail.com> wrote:
> Thank you for your answer.

You're welcome.

> Some things are still not clear. Your example works great. But if I
> remove "super(SuperClass1, self).__init__(**kwds)" from SuperClass1's
> __init__, the example stops working. That is when I instantiate
> SubClass only __init__ of SuperClass1 is called and __init__ of
> SuperClass2 is omitted, i.e. only 'Python' is printed. Why is it so?
>
> So as I understand every parent should necessarily call super() at the
> end of its __init__ method in order for things to work properly.

Yes.  That's correct.  Python's super() was designed to support
cooperative multiple inheritance.  The "cooperative" part means that
every class implementing the target method (such as __init__ in your
example) needs to call super() in order to trigger the next method in
the sequence (the method resolution order or MRO).


> But what if SuperClass1 is from third party library?
  . . .
> How to deal with that?

Then, the odds are that that class isn't "cooperating".  You can
either wrap the third-party library to add a super() call or you can
switch to an alternate design using composition instead of
inheritance.


Raymond


P.S.  Outside of the simple case of single inheritance, the one key to
understanding super() is to forget about the concept of parent
classes.  Instead, super() is all about the MRO which is computed
dynamically (unknowable at the time a class is written).  Every class
in the MRO implementing the target method *must* call super() to give
the next class in the MRO a chance to run.

IOW, using super() means "I'm in the MRO and I got a chance to run;
now the next class in the MRO gets its chance."   Since the MRO is
only knowable at runtime, the sole job of super() is to figure out
which is "the next class in the MRO".



More information about the Python-list mailing list