2010-01-28 17 views
28

¿Cómo me refiero this_prize.left o this_prize.right usando una variable?Acceso a un atributo mediante una 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' 
+5

FYI - Puede omitir la importación colecciones y sólo tiene que utilizar un diccionario para hacer la misma cosa: >>> this_prize = { "izquierda": "FirstPrize "," derecha ":" FirstPrize "} >>> this_prize [choice] > 'FirstPrize' –

+0

Relacionado: http://stackoverflow.com/questions/1167398/python-access-class-property-from-string –

Respuesta

52

La expresión this_prize.choice es decirle al intérprete que desea acceder a un atributo de this_prize con el nombre de "elección". Pero este atributo no existe en this_prize.

lo que realmente quiere es regresar el atributo de this_prize identificado por el valor de elección. Por lo que sólo necesita cambiar su última línea ...

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) 
47
+1

Creo que esta es la forma genérica para realizar la tarea. Ya que hace uso de la función integrada diseñada para el propósito, en realidad debería ser la respuesta preferida. (Sí, me di cuenta que es una vieja pregunta, pero sigue apareciendo en Google). – monotasker

Cuestiones relacionadas