首页 > 解决方案 > 获取具有字符串名称的对象的属性

问题描述

当我有我想要的属性名称字符串时,如何获取对象的属性值?例如,假设cmd_i有属性q0q1。我希望能够做到这一点:

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

而不必这样做:

print(cmd_i.q0)
print(cmd_i.q1)

标签: pythonstringfunction

解决方案


您可以使用getattr字符串来获取对象的属性值:

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

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

并使用 f 字符串:

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

如果属性不存在(而不是引发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

推荐阅读