Python - attributes of access objects, as in a dictionary

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

How can I access the fields my_objectdefined on my_str?

+6
source share
4 answers
getattr(my_object, my_str)

Learn more about getattr.

+20
source
>>> myobject.__dict__[my_str]
'stuff'
+1
source

You cannot run __dict__-approach altogether. What will always work

getattr(myobject, my_str)

If you need type access, just define a class with an overloaded operator index.

+1
source

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

0
source

All Articles