从列表中获取对象的属性

时间:2013-10-27 13:52:23

标签: 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:
    print(customer.a)    # This doesn't work!
    print(customer[a])    # Neither does this!

我专门针对Python3(Debian Linux),但也欢迎Python2答案。

1 个答案:

答案 0 :(得分:3)

使用getattr

getattr(customer, a)

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