下面的示例来自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)
does the same thing as 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”)。
关于python - 为什么getattr()比self .__ dict __。get()慢得多?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9790991/