【问题标题】:Passing a class attribute as a function argument?将类属性作为函数参数传递?
【发布时间】:2017-02-14 19:22:38
【问题描述】:

我可以将我正在寻找的变量名作为参数传递吗?在下面的 def 中,stat 参数用于更新函数中的 .stat。 (见箭头)我不断收到错误消息:

 print("game result :" +(self._playerHxDic[name][str(i)].stat))

AttributeError: 'GameHx' 对象没有属性 'stat'

def getStats(self,name,num_of_games,stat):
    games = self._playerHxDic[name].keys()
    gameNums = []
    for i in games:
        gameNums.append(int(i))
    gameNums.sort()
    if len(gameNums) > num_of_games:
        gamelist = [int(x) for x in gameNums[-num_of_games:]]
        points = 0
        for i in gamelist:
            points += statDicint(self._playerHxDic[name][i].stat)#<-- 
        return points/num_of_games
    else: return None

【问题讨论】:

  • 你想做什么?更新 GameHx 的 stat 变量?从 GameHx 对象中获取 stat 变量?请澄清您的问题。
  • 解决了!我需要 .__getattribute__(stat)) 方法

标签: python


【解决方案1】:
getattr(self._playerHxDic[name][i], stat)

Documentation of getattr()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2014-10-18
    相关资源
    最近更新 更多