2013-10-27 144 views
0

考慮對象customer和屬性列表attrs如何迭代列表以獲取列表中的屬性?從列表中獲取對象的屬性

class Human():  
    name = 'Jenny'   
    phone = '8675309' 

customer = Human() 
attrs = ['name', 'phone'] 

print(customer.name) # Jenny 
print(customer.phone) # 8675309 

for a in attrs: 
    print(customer.a) # This doesn't work! 
    print(customer[a]) # Neither does this! 

我專門針對Python3(Debian的Linux的),但Python2答案將受到歡迎,以及。

回答

3

使用getattr

getattr(customer, a) 

>>> class Human: 
...  name = 'Jenny' 
...  phone = '8675309' 
... 
>>> customer = Human() 
>>> for a in ['name', 'phone']: 
...  print(getattr(customer, a)) 
... 
Jenny 
8675309 
+0

大,謝謝! – dotancohen