>>> 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 ?
>>> 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] ? better performance ?try: or add if hasattr( before using getattr to make sure you're not trying to access something that's not there.getattr does not throw an exception if the attribute doesn't exist. It's basically syntactic sugar for if hasattr give me that else give me the default.getattr(my_object, my_str, None).>>> myobject.__dict__[my_str]
'stuff'
getattr(my_object, my_str) is better for performance also ?