为什么要使用 setattr() 和 getattr() 内置函数? [英] Why use setattr() and getattr() built-ins?

查看:60
本文介绍了为什么要使用 setattr() 和 getattr() 内置函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过阅读文档,我完全理解了 getattr()setattr() 做.但它也明确表示 getattr(x, 'foobar') 等价于 x.foobarsetattr(x, 'foobar', 123) 等价于 x.foobar = 123.

那我为什么要使用它们?

解决方案

因为你也可以使用动态变量:

somevar = 'foo'getattr(x, somevar)

使用常规属性访问语法无法做到这一点.

请注意,getattr() 还采用可选的默认值,如果属性缺失,则返回:

<预><代码>>>>x = 对象()>>>getattr(x, 'foo')回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>AttributeError: 'object' 对象没有属性 'foo'>>>getattr(x, 'foo', 42)42

使用 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() 内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆