Python - Access object attributes as in a dictionary

13,171

Solution 1

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.

Solution 2

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

Share:
13,171
Pierre de LESPINAY
Author by

Pierre de LESPINAY

Web developer at Masao. Fan of Django/python, Symfony/php, Vue/javascript, Docker EPITECH promo 2004.

Updated on June 13, 2022

Comments

  • Pierre de LESPINAY
    Pierre de LESPINAY almost 2 years
    >>> 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 ?

  • Admin
    Admin over 12 years
    Note that this breaks for properties, __slots__ and __getattr__/__getattribute__/__setattr__ overloads - and probably some other things.
  • Pierre de LESPINAY
    Pierre de LESPINAY over 12 years
    What is the advantage against myobject.__dict__[my_str] ? better performance ?
  • Pierre de LESPINAY
    Pierre de LESPINAY over 12 years
    Ok thank you for the info. Do you think getattr(my_object, my_str) is better for performance also ?
  • Admin
    Admin over 12 years
    Performance is your least concern here. If it is, you could rewrite that part (i.e. the whole loop, to avoid many cross-language calls) in C, but you should have solid proof of an unacceptable slowdown before considering such optimizations.
  • Tom
    Tom over 12 years
    Can I fall back on the standard "It's more Pythonic" answer? Also, tapping into the private __ variables comes with its own set of risks. What you're trying to do is what getattr and setattr are for.
  • oriadam
    oriadam over 8 years
    Word of warning though - if you use dynamic attribute names you should either use try: or add if hasattr( before using getattr to make sure you're not trying to access something that's not there.
  • Tom
    Tom over 8 years
    Huh? 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.
  • Tom
    Tom about 5 years
    To answer my own ignorance down the road that's because I was always passing a third argument for the default, e.g., getattr(my_object, my_str, None).
  • E. Zeytinci
    E. Zeytinci almost 4 years
    While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution.