【问题标题】:NameError when calling a class method调用类方法时出现 NameError
【发布时间】:2019-09-11 07:52:39
【问题描述】:

试图理解 Python 3.7 中的类和方法。我继续运行下面的代码,但不断收到这个 NameError,它与我在 Stats 类的初始化方法中建立的 points 变量相关联。我相信这个错误是由于识别局部/全局变量的一些问题造成的,但我不能指望它。有人有什么想法吗?

class Stats:
    def __init__(self, points, rebounds, assists, steals):
        self.points = points
        self.rebounds = rebounds
        self.assists = assists
        self.steals = steals

    def tripDub(self):
        if points >= 10 and rebounds >= 10 and assists >= 10 and steals >= 10:
            return "Yes!"
        else:
            return "Nope!"

s = Stats(30, 20, 9, 5)
print("Did he earn a Triple Double? Result:", s.tripDub())

【问题讨论】:

  • 在tripDub()方法中,你需要使用self来引用类变量。例如if self.points >= 10 and self.rebounds >= 10 and self.assists >= 10 and self.steals >= 10:
  • 如果有任何答案解决了您的问题,最好给他们投票并接受最好的答案。后者还给你一个小的代表奖金:)

标签: python class methods attributes nameerror


【解决方案1】:

在引用实例变量之前需要self.

class Stats:
    def __init__(self, points, rebounds, assists, steals):
        self.points = points
        self.rebounds = rebounds
        self.assists = assists
        self.steals = steals

    def tripDub(self):
        if self.points >= 10 and self.rebounds >= 10 and self.assists >= 10 and self.steals >= 10:
            return "Yes!"
        else:
            return "Nope!"


s = Stats(30, 20, 9, 5)
print("Did he earn a Triple Double? Result:", s.tripDub())

【讨论】:

    【解决方案2】:

    您需要在tripDub 函数中使用self 引用pointsreboundsassistssteals

    示例:self.points

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      相关资源
      最近更新 更多