0

How do I get the attribute value of an object when I have a string of the attribute name that I want? For example, suppose cmd_i has attributes q0 and q1. I'd like to be able to do this:

for x in range(2):                 
    print('cmd_i.q{}'.format(x))

Instead of having to do this:

print(cmd_i.q0)
print(cmd_i.q1)
random_forest_fanatic
  • 1,232
  • 1
  • 12
  • 30
I value -u 2
  • 107
  • 1
  • 4
  • What is cmd_i for you ? What are the value excepted to obtain with cmd_i.q0/1 ? We need more precision to provide you an answer ! – Xiidref Dec 06 '19 at 15:28

2 Answers2

1

You can use getattr to get attribute values of objects using strings:

class Test:
    q1 = 2
    q2 = 3
    q3 = 'a'

>>> x = Test()
>>> x.q1
2
>>> getattr(x, 'q2')
3

And with an f-string:

>>> for i in range(1, 4):
...     print(f'q{i}', getattr(x, f'q{i}'))
...
q1 2
q2 3
q3 a

You can also pass a default value to return if the attribute doesn't exist (instead of raising an AttributeError):

>>> getattr(x, 'q0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'q0'
# vs
>>> for i in range(1, 4):
...     print(f'q{i}', getattr(x, f'q{i}', None))
...
q0 None
q1 2
q2 3
q3 a
b_c
  • 1,202
  • 13
  • 24
0

It's also possible using the eval function, but doesn't seem to be considered good practice: https://stackoverflow.com/a/2909510/

a = 7
eval('a')
sammy
  • 857
  • 5
  • 13