Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an attribute using a variable in Python [duplicate]

Tags:

python

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' 
like image 645
Peter Stewart Avatar asked Jan 28 '10 18:01

Peter Stewart


People also ask

How do you make a variable an attribute in Python?

Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.

Are attributes and variables the same in Python?

An attribute behaves just like a variable in that it can reference any object without having to be declared as a specific type. Attributes are untyped. Now we have an example custom object, it is possible to demonstrate the idea that variables store references to objects.

Can we use same variable in Python?

In Python, we may reuse the same variable to store values of any type. A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times, and that storing a new value erases the old.

How do you print a variable name in Python?

Python print variables using a comma “,”: This method is another commonly used method in Python to print variables. This method is quite similar to the string concatenation method; however, here we use “,” between the variables.


Video Answer


2 Answers

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) 
like image 134
AJ. Avatar answered Oct 10 '22 20:10

AJ.


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

like image 42
S.Lott Avatar answered Oct 10 '22 20:10

S.Lott