在Python中使用变量访问属性

2024-09-30 22:18:42 发布

您现在位置: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'

Tags: thefromimportrightifrandomthisnamedtuple
2条回答

表达式this_prize.choice告诉解释器您想要访问名为“choice”的这个奖项的属性。但是这个属性在这个奖项中不存在。

您真正想要的是返回由所选的标识的这个奖项的属性。所以你只需要改变你的最后一行。。。

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)

相关问题 更多 >