TypeError: object.__init__() takes no parameters

Duncan Booth duncan.booth at invalid.invalid
Fri Sep 9 11:49:33 CEST 2011

Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915
@spamschutz.glglgl.de> wrote:

> Am 09.09.2011 07:47 schrieb Oliver:
>> class Container(object):
>>      """Container to store  a number of non-overlapping rectangles."""
>>      def __init__(self, xsize=1200, ysize=800):
>>          super(Container, self).__init__(xsize, ysize)
> And this is the nonsense: Container derives from object and tries to 
> call its superclass's constructor with 2 parameters - which won't work.
> Write this as super(Container, self).__init__().
It isn't nonsense, just poor and outdated practice. You might subclass 
Container with something that puts another base class into the mro between 
Container and object and in that case calling super(Container, self).
__init__() would be wrong.

object.__init__() used to accept and silently ignore any parameters. This 
meant you could safely pass any constructor parameters along in case there 
was an intervening base class that wanted them. However that was changed 
(presumably after this code was written) and now you have to be a bit more 
careful with your initialisation parameters.

This would be better in general, though if there is actually any code 
depending on xsize,ysize being passed up to a base class it will still need 
changing at the call site:

    def __init__(self, xsize=1200, ysize=800, *args, **kw):
          super(Container, self).__init__(*args, **kw)

That way any xsize and ysize arguments are removed but any additional 
arguments for other base classes are passed through.

Duncan Booth http://kupuguy.blogspot.com

More information about the Python-list mailing list