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")
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.
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, 2022Comments
-
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 onmy_str
? -
Admin over 12 yearsNote that this breaks for properties,
__slots__
and__getattr__/__getattribute__/__setattr__
overloads - and probably some other things. -
Pierre de LESPINAY over 12 yearsWhat is the advantage against
myobject.__dict__[my_str]
? better performance ? -
Pierre de LESPINAY over 12 yearsOk thank you for the info. Do you think
getattr(my_object, my_str)
is better for performance also ? -
Admin over 12 yearsPerformance 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 over 12 yearsCan 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 over 8 yearsWord of warning though - if you use dynamic attribute names you should either use
try:
or addif hasattr(
before usinggetattr
to make sure you're not trying to access something that's not there. -
Tom over 8 yearsHuh?
getattr
does not throw an exception if the attribute doesn't exist. It's basically syntactic sugar forif hasattr give me that else give me the default
. -
Tom about 5 yearsTo 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 almost 4 yearsWhile 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.