【问题标题】:Python self being ignored in a classPython self 在类中被忽略
【发布时间】: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)

标签: python class self


【解决方案1】:

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

CorrectChair.load(1) 替换为:

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

【讨论】:

  • 就是这样。加上其他错误。但这正是我想要的,谢谢!
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    在你的情况下,代码应该是:

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

    与您班级中的方法相比 - correct_chair对应self,1对应方法中的'number'

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      相关资源
      最近更新 更多