>>> 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?
my_object
my_str
getattr(my_object, my_str)
Learn more about getattr.
>>> myobject.__dict__[my_str] 'stuff'
You cannot run __dict__-approach altogether. What will always work
__dict__
getattr(myobject, my_str)
If you need type access, just define a class with an overloaded operator index.
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.
[]