11

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

1 回答 1

13

简而言之:因为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”)。

于 2012-03-20T16:38:12.643 回答