如何使用变量引用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'
http://docs.python.org/library/functions.html#getattr
表达式
this_prize.choice
告诉解释器您想要访问名为“choice”的这个奖项的属性。但是这个属性在这个奖项中不存在。您真正想要的是返回由所选的值标识的这个奖项的属性。所以你只需要改变你的最后一行。。。
相关问题 更多 >
编程相关推荐