Làm cách nào để tham chiếu this_prize.left
hoặc this_prize.right
bằng biến?Truy cập thuộc tính bằng biến trong 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'
FYI - Bạn có thể bỏ qua việc nhập khẩu các bộ sưu tập và chỉ sử dụng một từ điển để làm điều tương tự: >>> this_prize = { "left": "FirstPrize "," đúng ":" FirstPrize "} >>> this_prize [choice] > 'FirstPrize' –
Related: http://stackoverflow.com/questions/1167398/python-access-class-property-from-string –