因为您也可以使用动态变量:
somevar = 'foo'
getattr(x, somevar)
您无法使用常规属性访问语法来做到这一点。
注意getattr()
还采用可选的默认值,如果属性是则返回missing:
>>> x = object()
>>> getattr(x, 'foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
>>> getattr(x, 'foo', 42)
42
Using getattr()
您可以从其他内容中提取属性名称,而不是文字:
for attrname in dir(x):
print('x.{} = {!r}'.format(attrname, getattr(x, attrname))
或者你可以使用setattr()
设置动态属性:
for i, value in enumerate(dynamic_values):
setattr(i, 'attribute{}'.format(i), value)