开发者

Accessing an attribute using a variable in Python [duplicate]

开发者 https://www.devze.com 2022-12-18 14:19 出处:网络
This question already has answers here: How to access (get or set) object attribute given string corresponding to name of that attribute
This question already has answers here: How to access (get or set) object attribute given string corresponding to name of that attribute (3 answers) Closed 4 years ago.

How do I reference this_prize.left or this_prize.right using a vari开发者_运维百科able?

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'


The expression this_prize.choice is telling the interpreter that you want to access an attribute of this_prize with the name "choice". But this attribute does not exist in this_prize.

What you actually want is to return the attribute of this_prize identified by the value of choice. So you just need to change your last line using the getattr() method...

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)


getattr(this_prize, choice)

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

getattr(object, name) returns the value of the named attribute of object. name must be a string

0

精彩评论

暂无评论...
验证码 换一张
取 消