Search code examples
pythonobjectdictionary

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 ?


Solution

  • 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.