调用类方法时的NameError

问题描述 投票:-1回答:2

试图理解Python 3.7中的类和方法。我继续运行下面的代码,但继续得到这个NameError,与我在Stats类的initialize方法中建立的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())
python class methods attributes nameerror
2个回答
4
投票

在引用实例变量之前,您需要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())

3
投票

你需要在points函数中使用self来引用reboundsassistsstealstripDub

示例:self.points

© www.soinside.com 2019 - 2024. All rights reserved.