TypeError:__ init __()需要3个参数(给定2个)

Bil*_*der 5 python arguments class

我在这里看到了一些关于我的错误的答案,但它没有帮助我.我是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)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

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
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 10

该__init__()定义需要2个输入值,startValue和firstValue.您只提供了一个值.

def __init__(self, startValue, firstValue):

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

# Something like
a = SimpleCounter(5, 5)
Run Code Online (Sandbox Code Playgroud)

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

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


a = SimpleCounter(5)
Run Code Online (Sandbox Code Playgroud)


sen*_*rle 8

你__init__()定义需要双方一startValue 和一firstValue.所以你必须通过两个(即a = SimpleCounter(5, 5))来使这个代码工作.

但是,我觉得这里有一些更深层次的困惑:

class SimpleCounter():

    def __init__(self, startValue, firstValue):
        firstValue = startValue
        self.count = startValue
Run Code Online (Sandbox Code Playgroud)

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

class SimpleCounter():

    def __init__(self, startValue):
        self.firstValue = startValue
        self.count = startValue
Run Code Online (Sandbox Code Playgroud)