2010-01-28 36 views
28

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' 
+5

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' –

+0

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

Trả lời

52

Khái niệm this_prize.choice đang nói với người phiên dịch mà bạn muốn truy cập một thuộc tính của this_prize với cái tên "sự lựa chọn". Nhưng thuộc tính này không tồn tại trong this_prize.

Điều bạn thực sự muốn là trả lại thuộc tính của this_prize được xác định theo giá trị giá trị lựa chọn. Vì vậy, bạn chỉ cần thay đổi dòng cuối cùng của bạn ...

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

Tôi nghĩ đây là cách chung để hoàn thành nhiệm vụ. Vì nó sử dụng chức năng dựng sẵn được thiết kế cho mục đích nên nó thực sự là câu trả lời được ưu tiên. (Có, tôi nhận ra đây là một câu hỏi cũ nhưng nó vẫn xuất hiện trong Google.) – monotasker

Các vấn đề liên quan