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

Piet van Oostrum piet at vanoostrum.org
Sat Sep 29 17:51:29 EDT 2012


Chris Angelico <rosuav at gmail.com> writes:

> On Sun, Sep 30, 2012 at 3:17 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> No. Only add code that works and that you need. Arbitrarily adding calls
>> to the superclasses "just in case" may not work:
>>
>> py> class Spam(object):
>> ...     def __init__(self, x):
>> ...             self.x = x
>> ...             super(Spam, self).__init__(x)
>> ...
>> py> x = Spam(1)
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>>   File "<stdin>", line 4, in __init__
>> TypeError: object.__init__() takes no parameters
>
> That's because you're subclassing something that doesn't take
> parameters and giving it parameters. Of course that won't work. The
> normal and logical thing to do is to pass on only the parameters that
> you know the parent class expects... but that implies knowing the
> parent, so it's kinda moot.

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.
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list