【发布时间】:2018-07-09 03:11:14
【问题描述】:
我正在使用“学习 python 3 的插图指南”来学习 python。第 21 章是关于类的。在本章中,它显然错误地使用了“自我”?我尝试为示例编写自己的代码,但它不起作用,所以我输入了示例代码,令人惊讶的是,它也不起作用。
class CorrectChair:
'''blah'''
max_occupants = 4
def __init__(self, id):
self.id = id
self.count = 0
def load(self, number):
new_val = self.check(self.count + number)
self.count = new_val
def unload(self, number):
new_val - self._check(self.count - number)
self.count = new_val
def _check(self, number):
if number < 0 or number > self.max_occupants:
raise ValueError('Invalid count:{}'.format(number))
return number
它出错了:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
CorrectChair.load(1)
TypeError: load() missing 1 required positional argument:
'number'
似乎无法识别 self 参数。我该如何解决这个问题?谷歌搜索没有帮助,我看到的每个例子都让它看起来应该有效。
它应该将 (number) 添加到 self.count,而不是忽略它的自引用,并要求第二个参数。
【问题讨论】:
-
你没有实例化你的类。您似乎正在这样做 ->
CorrectChair.load(1),而实际上您想做类似CorrectChair(1).load(1)的事情。注意CorrectChair之后的括号 -
我建议首先将您的实例保存在一个变量中,然后进行调用 ->
correct_chair = CorrectChair(1)。然后你可以调用你的实例方法 ->correct_chair.load(1)