15

このコードを考えてみましょう:

class Foo1(dict):
    def __getattr__(self, key): return self[key]
    def __setattr__(self, key, value): self[key] = value

class Foo2(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__

o1 = Foo1()
o1.x = 42
print(o1, o1.x)

o2 = Foo2()
o2.x = 42
print(o2, o2.x)

私は同じ出力を期待します。ただし、CPython 2.5、2.6(3.2でも同様)を使用すると、次のようになります。

({'x': 42}, 42)
({}, 42)

PyPy 1.5.0を使用すると、期待どおりの出力が得られます。

({'x': 42}, 42)
({'x': 42}, 42)

「正しい」出力はどれですか?(または、Pythonのドキュメントによると出力はどうあるべきですか?)


これがCPythonのバグレポートです。

4

3 に答える 3

7

ルックアップの最適化に関係しているのではないかと思います。ソースコードから:

 /* speed hack: we could use lookup_maybe, but that would resolve the
       method fully for each attribute lookup for classes with
       __getattr__, even when the attribute is present. So we use
       _PyType_Lookup and create the method only when needed, with
       call_attribute. */
    getattr = _PyType_Lookup(tp, getattr_str);
    if (getattr == NULL) {
        /* No __getattr__ hook: use a simpler dispatcher */
        tp->tp_getattro = slot_tp_getattro;
        return slot_tp_getattro(self, name);
    }

高速パスは、クラスディクショナリでそれを検索しません。

したがって、目的の機能を取得するための最良の方法は、クラスにオーバーライドメソッドを配置することです。

class AttrDict(dict):
    """A dictionary with attribute-style access. It maps attribute access to
    the real dictionary.  """
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))

    def __setitem__(self, key, value):
        return super(AttrDict, self).__setitem__(key, value)

    def __getitem__(self, name):
        return super(AttrDict, self).__getitem__(name)

    def __delitem__(self, name):
        return super(AttrDict, self).__delitem__(name)

    __getattr__ = __getitem__
    __setattr__ = __setitem__

     def copy(self):
        return AttrDict(self)

私が見つけたものは期待通りに機能します。

于 2011-06-10T11:30:15.680 に答える
3

これは、既知の(そしておそらくそれほどよくない)文書化された違いです。PyPyは関数と組み込み関数を区別しません。CPythonでは、関数はクラスに格納されたときに非バインドメソッドとしてバインドされます(__get__があります)が、組み込み関数はそうではありません(異なります)。

ただし、PyPyでは、組み込み関数はPython関数とまったく同じであるため、インタープリターはそれらを区別できず、Pythonレベルの関数として扱います。この特定の違いを取り除くことについてpython-devでいくつかの議論がありましたが、これは実装の詳細として定義されたと思います。

乾杯、
フィジャル

于 2011-06-10T11:26:41.387 に答える
1

次の点に注意してください。

>>> dict.__getitem__ # it's a 'method'
<method '__getitem__' of 'dict' objects> 
>>> dict.__setitem__ # it's a 'slot wrapper'
<slot wrapper '__setitem__' of 'dict' objects> 

>>> id(dict.__dict__['__getitem__']) == id(dict.__getitem__) # no bounding here
True
>>> id(dict.__dict__['__setitem__']) == id(dict.__setitem__) # or here either
True

>>> d = {}
>>> dict.__setitem__(d, 1, 2) # can be called directly (since not bound)
>>> dict.__getitem__(d, 1)    # same with this
2

これで、それらをラップすることができます(それ__getattr__がなくても機能します):

class Foo1(dict):
    def __getattr__(self, key): return self[key]
    def __setattr__(self, key, value): self[key] = value

class Foo2(dict):
    """
    It seems, 'slot wrappers' are not bound when present in the __dict__ 
    of a class and retrieved from it via instance (or class either).
    But 'methods' are, hence simple assignment works with __setitem__ 
    in your original example.
    """
    __setattr__ = lambda *args: dict.__setitem__(*args)
    __getattr__ = lambda *args: dict.__getitem__(*args) # for uniformity, or 
    #__getattr__ = dict.__getitem__                     # this way, i.e. directly


o1 = Foo1()
o1.x = 42
print(o1, o1.x)

o2 = Foo2()
o2.x = 42
print(o2, o2.x)

これは次のようになります。

>>>
({'x': 42}, 42)
({'x': 42}, 42)

問題の動作の背後にあるメカニズムは(おそらく私は専門家ではありません)Pythonの「クリーンな」サブセットの外側にあります(「Pythonの学習」や「Pythonの概要」などの完全な本に記載されており、Pythonでやや大まかに指定されています。 org)であり、実装によって「現状のまま」文書化されている言語の部分に関係します(そして(むしろ)頻繁に変更される可能性があります)。

于 2011-06-17T23:12:05.993 に答える