问题描述
通过阅读文档,我完全理解了 getattr() 和 setattr() 做.但它也明确表示 getattr(x, 'foobar')
等价于 x.foobar
和 setattr(x, 'foobar', 123)
等价于 x.foobar = 123
.
那我为什么要使用它们?
因为你也可以使用动态变量:
somevar = 'foo'getattr(x, somevar)
使用常规属性访问语法无法做到这一点.
请注意,getattr()
还采用可选的默认值,如果属性缺失,则返回:
使用 getattr()
您可以从其他东西中提取属性名称,而不是文字:
用于 dir(x) 中的 attrname:print('x.{} = {!r}'.format(attrname, getattr(x, attrname))
或者你可以使用setattr()
来设置动态属性:
for i, value in enumerate(dynamic_values):setattr(i, 'attribute{}'.format(i), value)
From reading the docs, I understand exactly what getattr() and setattr() do. But it also says explicitly that getattr(x, 'foobar')
is equivalent to x.foobar
and setattr(x, 'foobar', 123)
is equivalent to x.foobar = 123
.
So why would I use them?
Because you can use a dynamic variable too:
somevar = 'foo'
getattr(x, somevar)
You can't do that with regular attribute access syntax.
Note that getattr()
also takes an optional default value, to be returned if the attribute is 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()
you can pull the attribute name from something else, not a literal:
for attrname in dir(x):
print('x.{} = {!r}'.format(attrname, getattr(x, attrname))
or you can use setattr()
to set dynamic attributes:
for i, value in enumerate(dynamic_values):
setattr(i, 'attribute{}'.format(i), value)
这篇关于为什么要使用 setattr() 和 getattr() 内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!