【问题标题】:Python inheritance: TypeError: object.__init__() takes no parametersPython继承:TypeError:object.__init__()不带参数
【发布时间】:2012-06-26 02:22:29
【问题描述】:

我收到此错误:

TypeError: object.__init__() takes no parameters 

在运行我的代码时,我真的看不出我在这里做错了什么:

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')

【问题讨论】:

    标签: python inheritance


    【解决方案1】:

    您在 super() 调用中调用了错误的类名:

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

    基本上你要解决的是对象基类的__init__,它不带参数。

    我知道,必须指定您已经在其中的类有点多余,这就是为什么在 python3 中您可以这样做:super().__init__()

    【讨论】:

    • @LucasKauffman:其实我不认为你很傻。它很容易成为一个令人困惑的概念。我不怪你。
    • 冒着冒犯许多 Pythonians 的风险:这 - 恕我直言 - 是糟糕的语言设计。感谢您的帮助@jdi!
    • @JohannesFahrenkrug - 我不认为你会冒犯任何人,因为这被认为是一个糟糕的设计并在 python3 中修复:docs.python.org/3/library/functions.html#super
    【解决方案2】:

    这让我最近两次受苦(我知道我第一次应该从我的错误中吸取教训)并且接受的答案两次都没有帮助我,所以当我记忆犹新时,我想我会提交自己的答案以防万一其他人遇到这个问题(或者我以后需要这个)。

    在我的情况下,问题是我将 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
    

    所以要解决这个问题,我只需要改变我在 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
    

    【讨论】:

      猜你喜欢
      • 2019-10-17
      • 2011-07-30
      • 1970-01-01
      • 2017-10-02
      • 2019-02-05
      • 2012-01-31
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多