使用Python中的变量访问属性

Accessing an attribute using a variable in Python

本问题已经有最佳答案,请猛点这里访问。

如何使用变量引用this_prize.leftthis_prize.right

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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'


表达的是"this_prize.choice告诉解释器,你想访问这个_属性与名称"选择"奖。但这属性不存在在这个_奖。

你真的想要这个属性返回的是_奖)的价值选择。那么你就需要改变你的载重线。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
getattr(this_prize,choice)

http://docs.python.org /图书馆/ functions.html # getattr