分配(而不是定义)__getitem__魔术方法会破坏索引

Nic*_*ens 6 python indexing class wrapper magic-methods

我有一个类似于这个(强烈简化)示例的包装类:

class wrap(object):
    def __init__(self):
        self._data = range(10)

    def __getitem__(self, key):
        return self._data.__getitem__(key)
Run Code Online (Sandbox Code Playgroud)

我可以像这样使用它:

w = wrap()
print w[2] # yields "2"
Run Code Online (Sandbox Code Playgroud)

我以为我可以通过改变这个来优化和摆脱一个函数调用:

class wrap(object):
    def __init__(self):
        self._data = range(10)
        self.__getitem__ = self._data.__getitem__
Run Code Online (Sandbox Code Playgroud)

但是,我收到了

TypeError:'wrap'对象不支持索引

对于print w[2]后一版本的行.

直接调用该方法,即print w.__getitem__(2)在两种情况下都有效...

为什么赋值版本不允许索引?

use*_*ica 5

Special methods (essentially anything with two underscores on each end) have to be defined on the class. The internal lookup procedure for special methods completely skips the instance dict. Among other things, this is so if you do

class Foo(object):
    def __repr__(self):
        return 'Foo()'
Run Code Online (Sandbox Code Playgroud)

the __repr__ method you defined is only used for instances of Foo, and not for repr(Foo).