如何使用变量引用this_prize.left
或this_prize.right
?
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right"])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
# retrieve the value of "left" or "right" depending on the choice
print("You won", this_prize.choice)
AttributeError: 'Prize' object has no attribute 'choice'
答案 0 :(得分:70)
表达式this_prize.choice
告诉解释器您想要使用名称“choice”访问this_prize的属性。但是this_prize中不存在此属性。
您真正想要的是返回由选择的 值 标识的this_prize的属性。所以你只需要改变你的最后一行......
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right" ])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
#retrieve the value of "left" or "right" depending on the choice
print "You won", getattr(this_prize,choice)
答案 1 :(得分:67)
getattr(this_prize,choice)