esp*_*eed 10 python getattr python-2.7
以下示例来自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
Run Code Online (Sandbox Code Playgroud)
Mar*_*cin 12
简而言之:因为getattr(foo,bar) 同样的事情foo.bar,这与访问该__dict__属性不同(为了一个开始,getattr必须选择正确的__dict__,但还有更多的事情发生).
此处包含或链接的详细信息:http://docs.python.org/reference/datamodel.html(搜索"getattr").