Accessing an attribute using a variable in Python

Python

Python Problem Overview


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'
    

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter StewartView Question on Stackoverflow
Solution 1 - PythonAJ.View Answer on Stackoverflow
Solution 2 - PythonS.LottView Answer on Stackoverflow