Подтвердить что ты не робот

Доступ к атрибуту с использованием переменной в Python

Как ссылаться на this_prize.left или this_prize.right с помощью переменной?

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'
4b9b3361

Ответ 1

Выражение this_prize.choice сообщает интерпретатору, что вы хотите получить доступ к атрибуту this_prize с именем "choice". Но этот атрибут не существует в this_prize.

То, что вы на самом деле хотите, - это вернуть атрибут this_prize, идентифицированный значением . Поэтому вам просто нужно изменить свою последнюю строку...

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)