考虑一个对象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答案。
答案 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