下面的示例来自 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