Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance: TypeError: object.__init__() takes no parameters

I get this error:

TypeError: object.__init__() takes no parameters  

when running my code, I don't really see what I'm doing wrong here though:

class IRCReplyModule(object):      activated=True     moduleHandlerResultList=None     moduleHandlerCommandlist=None     modulename=""      def __init__(self,modulename):         self.modulename = modulename   class SimpleHelloWorld(IRCReplyModule):       def __init__(self):             super(IRCReplyModule,self).__init__('hello world') 
like image 366
Lucas Kauffman Avatar asked Jun 24 '12 16:06

Lucas Kauffman


2 Answers

You are calling the wrong class name in your super() call:

class SimpleHelloWorld(IRCReplyModule):       def __init__(self):             #super(IRCReplyModule,self).__init__('hello world')             super(SimpleHelloWorld,self).__init__('hello world') 

Essentially what you are resolving to is the __init__ of the object base class which takes no params.

Its a bit redundant, I know, to have to specify the class that you are already inside of, which is why in python3 you can just do: super().__init__()

like image 148
jdi Avatar answered Sep 18 '22 04:09

jdi


This has bitten me twice recently (I know I should have learned from my mistake the first time) and the accepted answer hasn't helped me either time so while it is fresh in my mind I thought I would submit my own answer just in case anybody else is running into this (or I need this again in future).

In my case the issue was that I was passing a kwarg into the initialisation of the subclass but in the superclass that keyword arg was then being passed though into the super() call.

I always think these types of things are best with an example:

class Foo(object):   def __init__(self, required_param_1, *args, **kwargs):     super(Foo, self).__init__(*args, **kwargs)     self.required_param = required_param_1     self.some_named_optional_param = kwargs.pop('named_optional_param', None)    def some_other_method(self):     raise NotImplementedException  class Bar(Foo):   def some_other_method(self):     print('Do some magic')   Bar(42) # no error Bar(42, named_optional_param={'xyz': 123}) # raises TypeError: object.__init__() takes no parameters 

So to resolve this I just need to alter the order that I do things in the Foo.__init__ method; e.g.:

class Foo(object):   def __init__(self, required_param_1, *args, **kwargs):     self.some_named_optional_param = kwargs.pop('named_optional_param', None)     # call super only AFTER poping the kwargs     super(Foo, self).__init__(*args, **kwargs)     self.required_param = required_param_1 
like image 37
John Avatar answered Sep 18 '22 04:09

John