相关疑难解决方法(0)

在新式类中实现__getitem__

我有这个代码:

class A:
    def __init__(self):
        def method(self, item):
            print self, ": Getting item", item
        self.__getitem__ = types.MethodType(method, self, self.__class__)

class B(object):
    def __init__(self):
        def method(self, item):
            print self, ": Getting item", item
        self.__getitem__ = types.MethodType(method, self, self.__class__)
Run Code Online (Sandbox Code Playgroud)

然后这工作正常:

a = A()
a[0]
Run Code Online (Sandbox Code Playgroud)

但这不是:

b = B()
b[0]
Run Code Online (Sandbox Code Playgroud)

引发TypeError.

我发现新式类在类__dict__中寻找魔术方法而不是实例__dict__.这是正确的吗?为什么会这样?你知道任何解释背后的想法的文章吗?我试过RTFM,但也许不是正确的或没有抓到的东西......

非常感谢你!保罗

python python-2.7

5
推荐指数
1
解决办法
2690
查看次数

标签 统计

python ×1

python-2.7 ×1