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

Raymond Hettinger python at rcn.com
Fri Jul 30 12:34:13 EDT 2010


On Jul 25, 5:30 pm, Gregory Ewing <greg.ew... at canterbury.ac.nz> wrote:
> Raymond Hettinger wrote:
> > Every class
> > in the MRO implementing the target method *must* call super() to give
> > the next class in the MRO a chance to run.
>
> EXCEPT for the last one, which must NOT call super!
>
> The posted example happens to work because object has
> a default __init__ method that does nothing. But this
> is not generally true of other methods, which means you
> need a "terminating" class at the end of the MRO whose
> methods don't call super.

That is an important point and it is what Guido does in his examples:
http://www.python.org/download/releases/2.2.3/descrintro/#cooperation

The design options are:

* if overriding a method provided by object() such as __init__(),
__getattribute__() or __setattr__(), then you should call super() in
each class that overrides or extends those methods.

* if you know the whole class structure in advance, you call super()
in every class except the last one -- that is what Guido does in the
save() example.

* if you don't know the whole class structure in advance, then you
can't be sure which is that last class in the mro with the target
method, so you need to wrap the super() call in a try / except
AttributeError

Raymond





More information about the Python-list mailing list