我有这个代码:
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__)
然后这工作正常:
a = A()
a[0]
但这不会:
b = B()
b[0]
引发类型错误。
我发现新式类在类 __dict__ 而不是实例 __dict__ 中寻找魔术方法。这是正确的吗?为什么会这样?你知道任何解释背后想法的文章吗?我尝试了 RTFM,但可能不是正确的,或者没有抓住东西......
非常感谢!保罗