Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46178

Python - Access object attributes as in a dictionary

>>> my_object.name = 'stuff'
>>> my_str = 'name'
>>> my_object[my_str] # won't work because it's not a dictionary :)

How can I access to the fields of my_object defined on my_str ?

Upvotes: 11

Views: 18337

Answers (4)

Tom
Tom

Reputation: 22841

getattr(my_object, my_str)

Or, if you're not sure if the name exists as a key and want to provide a fallback instead of throwing an exception:

getattr(my_object, my_str, "Could not find anything")

More on getattr.

Upvotes: 28

Laizer
Laizer

Reputation: 6140

You can provide support for the [] operator for objects of your class by defining a small family of methods - getitem and setitem, principally. See the next few entries in the docs for some others to implement, for full support.

Upvotes: 4

filmor
filmor

Reputation: 32202

You can't do the __dict__-approach in general. What will always work is

getattr(myobject, my_str)

If you want dict-like access, just define a class with an overloaded index-operator.

Upvotes: 0

Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46178

>>> myobject.__dict__[my_str]
'stuff'

Upvotes: 0

Related Questions