在Python中使用变量访问属性

71 投票
2 回答
78486 浏览
提问于 2025-04-15 18:36

我该如何用一个变量来引用 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 个回答

113
getattr(this_prize, choice)

来自 http://docs.python.org/library/functions.html#getattr:

getattr(object, name) 这个函数会返回对象中指定属性的值。这里的 name 必须是一个字符串。

111

表达式 this_prize.choice 是在告诉解释器,你想要访问名为 "choice" 的这个_prize 的一个属性。但是,这个属性在 this_prize 中并不存在。

你实际上想要的是根据 choice 的 来返回 this_prize 的一个属性。所以你只需要在最后一行使用 getattr() 方法来进行修改...

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)

撰写回答