如何引用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'
Run Code Online (Sandbox Code Playgroud)
AJ.*_*AJ. 77
表达式this_prize.choice告诉解释器您要使用名称"choice"访问this_prize的属性.但是this_prize中不存在此属性.
你真正想要的是返回由choice 值标识的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)
Run Code Online (Sandbox Code Playgroud)
S.L*_*ott 72
getattr(this_prize,choice)
Run Code Online (Sandbox Code Playgroud)
http://docs.python.org/library/functions.html#getattr
| 归档时间: |
|
| 查看次数: |
38687 次 |
| 最近记录: |