dotancohen
dotancohen

Reputation: 31471

Get properties of object from list

Consider an object customer and a list of properties attrs. How might one iterate over the list to get the properties from the list?

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!

I am specifically targeting Python3 (Debian Linux) but a Python2 answer would be welcome as well.

Upvotes: 0

Views: 190

Answers (1)

falsetru
falsetru

Reputation: 369054

Use getattr:

getattr(customer, a)

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

Upvotes: 3

Related Questions