Python TypeError:\uuuu init\uuuuuu()正好接受3个参数(给定2个)
我在这里看到了一些关于我的错误的答案,但这对我没有帮助。我绝对是python类的noob,早在九月份就开始编写这段代码了。无论如何,看看我的代码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
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新样式类)