使用Python中的变量访问属性

Pet*_*art 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'
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

  • 我认为这是完成任务的通用方法。由于它使用了为此目的而设计的内置函数,因此它确实应该是首选答案。(是的,我意识到这是一个老问题,但它仍然出现在 Google 中。) (2认同)
  • 并且,对应的自然是“setattr”。`setattr(x, 'foobar', 123)` 与 `x.foobar = 123` 相同。 (2认同)