74

How do I reference this_prize.left or this_prize.right using a variable?

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
  • 5
    FYI - You can skip the collections import and just use a dictionary to do the same thing: >>> this_prize = {"left": "FirstPrize", "right":"FirstPrize"} >>> this_prize[choice] >'FirstPrize' Commented Jan 28, 2010 at 18:59
  • Related: stackoverflow.com/questions/1167398/… Commented Jan 28, 2010 at 19:00

2 Answers 2

119
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

Sign up to request clarification or add additional context in comments.

2 Comments

I think this is the generic way to accomplish the task. Since it makes use of the built-in function designed for the purpose, it should really be the preferred answer. (Yes, I realize this is an old question, but it still shows up in Google.)
And, naturally the counterpart is setattr. setattr(x, 'foobar', 123) is the same as x.foobar = 123.
112

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.