Should one always add super().__init__() to the __init__?

Manuel Pégourié-Gonnard mpg at elzevir.fr
Sun Sep 30 08:04:04 EDT 2012


Steven D'Aprano scripsit :

> On Sun, 30 Sep 2012 00:08:03 -0600, Ian Kelly wrote:
>
>> On Sat, Sep 29, 2012 at 10:40 PM, Steven D'Aprano
>> <steve+comp.lang.python at pearwood.info> wrote:
>>> On Sat, 29 Sep 2012 17:51:29 -0400, Piet van Oostrum wrote:
>>>
>>>> It is not necesarily calling the parent class. It calls the
>>>> initializer of the next class in the MRO order and what class that is
>>>> depends on the actual multiple inheritance structure it is used in,
>>>> which can depend on subclasses that you don't know yet. This makes it
>>>> even worse.
>>>
>>> I don't quite follow you here. It sounds like you are saying that if
>>> you have these classes:
>>>
>>> # pre-existing classes
>>> class A(object): pass
>>> class B(object): pass
>>>
>>> # your class
>>> class C(A, B): pass
>>>
>>> and somebody subclasses A or B, the MRO of C will change. That is not
>>> actually the case as far as I can see.
>> 
>> The MRO of C will not change, but the class that follows C may be
>> different in the MRO of a subclass.
>
> To quote a famous line from the movie Cool Hand Luke, "what we have here, 
> is a failure to communicate."
>
> What do you mean by one class following another?  Which class is it
> that follows C? What subclass are you talking about, and what is it
> subclassing?
>
I think Piet's (and Ian's) point is, you can't assume that
super().__init__, written in a method of C, is always going to refer to
__init__ of the parent class of C, when a subclass of C is instanciated.

For example:

class C:
    def __init__(self):
        print("C init, calling C's parent init?")
        super().__init__() # sic

class NotParentOfC:
    def __init__(self):
        print("NotParentOfC init")

class Sub(C, NotParentOfC):
    pass

spam = Sub()

When Sub is instantiated, the line marked "sic" calls
NotParentOfC.__init, not object.__init__ (as if would if C was
instantiated).

-- 
Manuel Pégourié-Gonnard - http://people.math.jussieu.fr/~mpg/






More information about the Python-list mailing list