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