Python 从列表中获取对象的属性

Python 从列表中获取对象的属性,python,Python,考虑一个对象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: pr

考虑一个对象
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问题。

使用:


使用:


使用:


使用:


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