[英]Why is getattr() so much slower than self.__dict__.get()?
下面的示例来自 Python 2.7 上的 REST 数据库驱动程序。
在下面的__setattr__
方法中,如果我使用注释掉的getattr()
行,它会将对象实例化性能从 600 rps 降低到 230。
在这种情况下,为什么getattr()
比self.__dict__.get()
慢这么多?
class Element(object):
def __init__(self, client):
self._client = client
self._data = {}
self._initialized = True
def __setattr__(self, key, value):
#_initialized = getattr(self, "_initialized", False)
_initialized = self.__dict__.get("_initialized", False)
if key in self.__dict__ or _initialized is False:
# set the attribute normally
object.__setattr__(self, key, value)
else:
# set the attribute as a data property
self._data[key] = value
简而言之:因为getattr(foo,bar)
与foo.bar
做同样的事情,这与仅访问__dict__
属性不同(首先, getattr
必须选择正确的__dict__
,但还有更多继续)。
举例说明:
>>> class A:
... a = 1
...
>>> class B(A):
... b = 2
...
>>> dir(B)
['__doc__', '__module__', 'a', 'b']
>>> B.a
1
>>> B.__dict__
{'__module__': '__main__', 'b': 2, '__doc__': None}
>>> B.__dict__['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> B.__dict__.get('a')
>>>
此处包含或链接到的详细信息: http : //docs.python.org/reference/datamodel.html (搜索“getattr”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.