2013-10-27 2 views
0

오브젝트 customer과 특성 목록 attrs을 고려하십시오. 목록에서 속성을 가져 오기 위해 어떻게 목록을 반복 할 수 있습니까? 내가 특별히 Python3 (데비안 리눅스)하지만 Python2 응답을 목표로하고리스트에서 오브젝트의 특성을 얻으십시오.

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! 

도 환영받을 것입니다.

답변

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

관련 문제