Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:\uuuu init\uuuuuu()正好接受3个参数(给定2个)_Python_Class_Arguments - Fatal编程技术网

Python TypeError:\uuuu init\uuuuuu()正好接受3个参数(给定2个)

Python TypeError:\uuuu init\uuuuuu()正好接受3个参数(给定2个),python,class,arguments,Python,Class,Arguments,我在这里看到了一些关于我的错误的答案,但这对我没有帮助。我绝对是python类的noob,早在九月份就开始编写这段代码了。无论如何,看看我的代码 class SimpleCounter(): def __init__(self, startValue, firstValue): firstValue = startValue self.count = startValue def click(self): self.count

我在这里看到了一些关于我的错误的答案,但这对我没有帮助。我绝对是python类的noob,早在九月份就开始编写这段代码了。无论如何,看看我的代码

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
回溯(最近一次呼叫最后一次):
文件“C:\Users\Bilal\Downloads\simplecounter.py”,第26行,在
a=简单计数器(5)
TypeError:\uuuu init\uuuuuu()正好接受3个参数(给定2个)
定义调用两个输入值,
startValue
firstValue
。您只提供了一个值

def __init__(self, startValue, firstValue):

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

# Something like
a = SimpleCounter(5, 5)
现在,您是否真的需要两个值是另一回事。
startValue
仅用于设置
firstValue
的值,因此您可以重新定义
\uuu init\uuu()
以仅使用一个值:

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


a = SimpleCounter(5)
您的
\uuu init\uuu()
定义既需要
起始值
又需要
第一值
。因此您必须同时通过这两个步骤(即
a=SimpleCounter(5,5)
)才能使此代码正常工作

然而,我得到的印象是,在工作中有一些更深层次的困惑:

class SimpleCounter():

    def __init__(self, startValue, firstValue):
        firstValue = startValue
        self.count = startValue
为什么要将
startValue
存储到
firstValue
中,然后将其丢弃?在我看来,您似乎错误地认为
\uuuu init\uuuuu
的参数会自动成为类的属性。事实并非如此。您必须显式地分配它们。因为这两个值都等于
startValue
,所以您不需要需要将其传递给构造函数。您只需将其分配给
self.firstValue
,如下所示:

class SimpleCounter():

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

仅供参考,您的类应该继承自
对象
(如果您想知道原因,请使用google for python新样式类)