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'
所以我想要做的就是使用每個目標作爲變量名稱,目的是減少代碼重複。我知道我可以很容易地複製粘貼功能幾次,但似乎很愚蠢。 目前上面的代碼不會將目標變量值識別爲變量而不是字符串。
任何答案將超級讚賞!
'GETATTR(匹配,目標)'。 –