blindsnowmobile
blindsnowmobile

Reputation: 4308

Python: Can you use an evaluated expression in an object reference?

I'm not sure the best way to ask this, so I'm going to try by example. Is there an easy way in Python to accomplish the following?

instead of referencing an object like this:

>> print myobject.someattrib
5

...use an expression which will be evaluated first, and then dereferenced?:

>> obj_name = "someattrib"
>> print myobject.<print value of obj_name>
5

Upvotes: 3

Views: 44

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122536

You can do:

print getattr(myobject, obj_name)

Upvotes: 7

Related Questions