使用Python中的变量访问属性

时间:2010-01-28 18:47:41

标签: python

如何使用变量引用this_prize.leftthis_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'

2 个答案:

答案 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)