【问题标题】:TypeError: __init__() takes exactly 3 arguments (2 given)TypeError: __init__() 正好需要 3 个参数(给定 2 个)
【发布时间】:2012-03-15 17:51:07
【问题描述】:

我在这里看到了一些关于我的错误的答案,但这对我没有帮助。我是 Python 课程的绝对菜鸟,并且在 9 月才开始编写此代码。无论如何看看我的代码

class SimpleCounter():

    def __init__(self, startValue, firstValue):
        firstValue = startValue
        self.count = startValue

    def click(self):
        self.count += 1

    def getCount(self):
        return self.count

    def __str__(self):
        return 'The count is %d ' % (self.count)

    def reset(self):
        self.count += firstValue

a = SimpleCounter(5)

这是我得到的错误

Traceback (most recent call last):
File "C:\Users\Bilal\Downloads\simplecounter.py", line 26, in <module>
a = SimpleCounter(5)
TypeError: __init__() takes exactly 3 arguments (2 given

【问题讨论】:

  • 仅供参考,您的类应该继承自 object(如果您好奇为什么,请在谷歌上找到 python 新型类)

标签: python class arguments


【解决方案1】:

__init__() 定义需要 2 个输入值,startValuefirstValue。您只提供了一个值。

def __init__(self, startValue, firstValue):

# Need another param for firstValue
a = SimpleCounter(5)

# Something like
a = SimpleCounter(5, 5)

现在,您是否真的需要 2 个值是另一回事。 startValue 仅用于设置firstValue 的值,因此您可以重新定义__init__() 以仅使用一个:

# No need for startValue
def __init__(self, firstValue):
  self.count = firstValue


a = SimpleCounter(5)

【讨论】:

    【解决方案2】:

    您的__init__() 定义需要两个 startValue firstValue。因此,您必须同时通过两者(即a = SimpleCounter(5, 5))才能使此代码正常工作。

    但是,我的印象是这里的工作存在一些更深层次的困惑:

    class SimpleCounter():
    
        def __init__(self, startValue, firstValue):
            firstValue = startValue
            self.count = startValue
    

    为什么要将startValue 存储到firstValue 然后扔掉?在我看来,您错误地认为__init__ 的参数会自动成为类的属性。事实并非如此。您必须明确分配它们。由于这两个值都等于startValue,因此您无需将其传递给构造函数。您可以像这样将其分配给self.firstValue

    class SimpleCounter():
    
        def __init__(self, startValue):
            self.firstValue = startValue
            self.count = startValue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多