【问题标题】:Attributes as function arguments属性作为函数参数
【发布时间】:2020-07-21 04:07:56
【问题描述】:

我定义了一个名为Score的类

class Score():
    
    def __init__(self, player, dealer):
        
        self.player = player
        self.dealer = dealer

score = Score(31,27)

之后我定义了一个名为change_score的函数,它对分数对象的属性值进行算术运算。

def change_score(i, attribute):
    
    if i > 0:
        score.attribute += 4
    else:
        score.attribute -= 1

    return score.attribute

但是,当我传递这样的属性时:

change_score(0, player)

弹出如下错误:NameError: name 'player' is not defined

那我该怎么做呢?

【问题讨论】:

    标签: python-3.x class object attributes


    【解决方案1】:

    解决此问题的更好方法是将函数添加到类中,以便更易于管理,并且您还需要在 init() 方法中定义属性使其和实例属性

    所以新代码是:

    class Score:
    
        def __init__(self, player, dealer): # add an the attribute here if you want
    
            self.player = player
            self.dealer = dealer
            self.attribute = 0 # Then set that attribute parameter here (if you want)
    
        def change_score(self, i):
            if i > 0:
                self.attribute += 4
            else:
                self.attribute -= 1
            return self.attribute
    

    类外添加:

    score = Score(31, 27)
    score.change_score(-1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      相关资源
      最近更新 更多