为什么getattr()比self慢得多.__ dict __。get()?

时间:2012-03-20 16:35:25

标签: python python-2.7 getattr

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

1 个答案:

答案 0 :(得分:12)

简而言之:因为getattr(foo,bar) does the same thing as foo.bar,这与访问__dict__属性不同(首先,getattr必须选择正确的__dict__ {1}},但还有很多事情要发生。)

此处包含或链接到此处的详细信息:http://docs.python.org/reference/datamodel.html(搜索“getattr”)。