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'
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With