Python自我在类中被忽略

时间:2018-07-09 03:11:15

标签: python class 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.count上加上(number),而不是忽略它的自引用,并要求第二个参数。

3 个答案:

答案 0 :(得分:0)

您必须创建一个实例并在其上调用方法:

CorrectChair.load(1)替换为:

c_chair = CorrectChair(some_id)
c_chair.load(1)

答案 1 :(得分:0)

load函数实际上是一个对象方法。在Python世界中,对象方法的第一个参数始终指向实例,实例将在调用前隐式传递给方法。要调用对象方法,首先需要创建一个对象,然后通过点语法调用该方法。当然

例如

id = 3
newCorrectChair = CorrectChair(id)

# self is implicitly passed here, this style stems from C.
CorrectChair(id).load(10) 

如果您尝试编写类方法,则必须添加一个@classmethod装饰器。

class CorrectChair:
    # Blah...
    @classmethod
    def load(cls, num):
        # do something
        return

如果您尝试编写静态函数,则应使用@staticmethod装饰器装饰该方法。

class CorrectChair:
    # Blah...
    @staticmethod
    def load(cls, num):
        # do something
        return

答案 2 :(得分:0)

该错误表明您正在尝试直接从类中调用方法, 而该方法也需要对象引用。 在对包含“ 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