猿问

Python自我在类中被忽略

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


慕的地10843
浏览 157回答 3
3回答

绝地无双

该load函数实际上是一个对象方法。在Python世界中,对象方法的第一个参数始终指向实例,实例将在调用前隐式传递给方法。要调用对象方法,首先需要创建一个对象,然后通过点语法调用该方法。当然例如id = 3newCorrectChair = CorrectChair(id)# self is implicitly passed here, this style stems from C.CorrectChair(id).load(10)&nbsp;如果您尝试编写类方法,则必须添加@classmethod装饰器。class CorrectChair:&nbsp; &nbsp; # Blah...&nbsp; &nbsp; @classmethod&nbsp; &nbsp; def load(cls, num):&nbsp; &nbsp; &nbsp; &nbsp; # do something&nbsp; &nbsp; &nbsp; &nbsp; return如果您尝试编写静态函数,则应使用@staticmethoddecorator装饰该方法。class CorrectChair:&nbsp; &nbsp; # Blah...&nbsp; &nbsp; @staticmethod&nbsp; &nbsp; def load(cls, num):&nbsp; &nbsp; &nbsp; &nbsp; # do something&nbsp; &nbsp; &nbsp; &nbsp; return

慕田峪7331174

您必须创建一个实例并在其上调用方法:替换CorrectChair.load(1)为:c_chair = CorrectChair(some_id)c_chair.load(1)

不负相思意

该错误表明您正在尝试直接从类中调用方法,而该方法也需要对象引用。在对包含“ self”的任何方法进行任何调用之前,需要首先创建该类的实例。在您的情况下,代码应为:correct_chair = CorrectChair(id)correct_chair.load(1)与您类中的方法比较-correct_chair对应于self,1对应于方法中的“数字”def load(self, number):&nbsp; &nbsp; new_val = self.check(self.count + number)&nbsp; &nbsp; self.count = new_val
随时随地看视频慕课网APP

相关分类

Python
我要回答