Luc*_*man 80 python inheritance
我收到此错误:
TypeError: object.__init__() takes no parameters
Run Code Online (Sandbox Code Playgroud)
在运行我的代码时,我并没有真正看到我在这里做错了什么:
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')
Run Code Online (Sandbox Code Playgroud)
jdi*_*jdi 103
您在super()调用中调用了错误的类名:
class SimpleHelloWorld(IRCReplyModule):
def __init__(self):
#super(IRCReplyModule,self).__init__('hello world')
super(SimpleHelloWorld,self).__init__('hello world')
Run Code Online (Sandbox Code Playgroud)
基本上你要解决的是__init__没有参数的对象基类.
我知道,它有点多余,必须指定你已经在其中的类,这就是为什么在python3中你可以这样做: super().__init__()
这最近让我痛苦了两次(我知道我应该从第一次的错误中吸取教训),并且接受的答案两次都没有帮助我,所以虽然它在我的脑海中是新鲜的,但我想我会提交我自己的答案,以防万一其他人也遇到了这个问题(或者我将来再次需要这个)。
就我而言,问题是我将 kwarg 传递到子类的初始化中,但在超类中,关键字 arg 然后被传递到 super() 调用中。
我一直认为这些类型的事情最好举个例子:
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
Run Code Online (Sandbox Code Playgroud)
因此,要解决这个问题,我只需要更改 Foo.__init__ 方法中执行操作的顺序即可;例如:
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
Run Code Online (Sandbox Code Playgroud)