Comment faire référence à this_prize.left
ou this_prize.right
en utilisant une variable?Accéder à un attribut en utilisant une variable en Python
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'
Pour votre information - Vous pouvez sauter les collections d'importation et il suffit d'utiliser un dictionnaire pour faire la même chose: >>> this_prize = { « gauche »: « FirstPrize "," right ":" FirstPrize "} >>> this_prize [choix] > 'FirstPrize' –
Connexe: http://stackoverflow.com/questions/1167398/python-access-class-property-from-string –