2017-05-09 66 views
0

我以前遇到过这个问题,从来没有找到解决方案。我检查了谷歌链接吨,仍然不知道。 我想要做的是使用一个字符串作为变量。我与SQLAlchemy的工作,所以会使用例如直接从我的项目:(寻找在函数变量“目标”)将字符串转换为变量或对象,Python

下面是一个例子:

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' 

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

任何答案将超级赞赏!

+0

'GETATTR(匹配,目标)'。 –

回答

1

好像你可以使用getattr

getattr(Match, objective) 
+0

感谢堆!爱SO社区! –