【问题标题】:Turning a string into variable or object, Python [duplicate]将字符串转换为变量或对象,Python [重复]
【发布时间】:2017-05-09 13:03:36
【问题描述】:

我过去遇到过这个问题,但从未找到解决方案。我检查了大量的谷歌链接,但仍然不知道。 我想要做的是使用字符串作为变量。我正在使用 SQLalchemy,因此将直接使用我项目中的示例:(在函数中查找变量“objective”)

这是一个例子:

def win_ratio_p_obj(objective):
    #want to find the win/loss ratio for each obj_first, ie. 60% of times when team gets fblood you also win vs. 40% of time you lose
    obj_totals = session.query(Match.win, func.count(Match.win)).filter(Match.**objective** == 't').group_by(Match.win).order_by(Match.win).all()
    win_chance = obj_totals[1][1]/(obj_totals[0][1]+obj_totals[1][1])
    return win_chance

objective = 'first_dragon'    
x = win_ratio_p_obj(objective)
objective = 'first_blood' 
y = win_ratio_p_obj(objective)
objective = 'first_turret' 
z = win_ratio_p_obj(objective)
objective = 'first_inhib'    

返回:

Traceback (most recent call last):
  Python Shell, prompt 15, line 1
builtins.AttributeError: type object 'Match' has no attribute 'objective'

所以我想做的是使用每个目标作为变量名,目的是减少代码重复。我知道我可以很容易地复制粘贴该功能几次,但这似乎很愚蠢。 目前,上面的代码不会将目标变量值识别为变量而不是字符串。

任何答案都将非常感谢!

【问题讨论】:

  • getattr(Match, objective).

标签: python sqlalchemy


【解决方案1】:

看来你可以使用getattr:

getattr(Match, objective)

【讨论】:

  • 非常感谢!喜欢 SO 社区!
猜你喜欢
  • 2013-04-20
  • 1970-01-01
  • 2013-01-12
  • 2011-09-21
  • 2013-10-07
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多