TypeError:__init __()只需要3个参数(给出2个参数)
问题描述:
我在这里看到了一些关于我的错误的答案,但它对我没有帮助。我是一个绝对的noob在Python上的类,并刚刚在9月份开始执行此代码。反正看看我的代码TypeError:__init __()只需要3个参数(给出2个参数)
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
答
你__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
答
的__init__()
清晰的通话2个输入值,startValue
和firstValue
。你只提供了一个值。
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)
据透露,你的类应该从'object'继承(谷歌的蟒蛇新样式类,如果你是好奇,为什么) – ThiefMaster 2012-02-25 14:54:56