python - 获取具有字符串名称的对象的属性
问题描述
当我有我想要的属性名称字符串时,如何获取对象的属性值?例如,假设cmd_i
有属性q0
和q1
。我希望能够做到这一点:
for x in range(2):
print('cmd_i.q{}'.format(x))
而不必这样做:
print(cmd_i.q0)
print(cmd_i.q1)
解决方案
您可以使用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
推荐阅读
- python-3.x - 您如何检查当前下载的版本并下载最新版本的 SymPy?
- php - Dompdf laravel 文本重叠
- azure-cosmosdb - Azure Cosmos Graph DB:获取 WebSocket 异常
- oracle-apex - 在 Apex 表单中创建即时验证
- scala - 具有相同根目录的多个 sbt 项目
- ios - Swift 检测视图的方向何时已经改变
- c# - 在运行新测试之前重新复制到输出目录
- python - ImportError:导入open3d时DLL加载失败:找不到指定的模块
- transform - Godot/Gdscript 旋转 + 从本地空间转换到世界空间
- cart - 修剪回归树cp选择或其他方式