>>> 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
?
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")
>>> myobject.__dict__[my_str]
'stuff'
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.