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 的答案。

4

1 回答 1

3

使用getattr

getattr(customer, a)

>>> class Human:
...     name = 'Jenny'
...     phone = '8675309'
...
>>> customer = Human()
>>> for a in ['name', 'phone']:
...     print(getattr(customer, a))
...
Jenny
8675309
于 2013-10-27T13:53:43.427 回答