首页 > 解决方案 > Python self 在类中被忽略

问题描述

我正在使用“学习 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,而不是忽略它的自引用,并要求第二个参数。

标签: pythonclassself

解决方案


该错误表明您正在尝试直接从类中调用方法,而该方法也需要对象引用。在调用任何包含“self”的方法之前,您需要先创建该类的实例

在您的情况下,代码应为:

correct_chair = CorrectChair(id)
correct_chair.load(1)

与您班级中的方法相比-correct_chair 对应于 self,1 对应于方法中的“数字”

def load(self, number):
    new_val = self.check(self.count + number)
    self.count = new_val

推荐阅读