在实例方法中指向类方法显然会导致问题:
class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() B.__getitem__ = self.a.__getitem__ b1 = B() b1.a['a'] = 5 b2 = B() b2.a['b'] = 10 c = b1['a'] d = b2['b']
给出了这个错误:
File ... in __getitem__ return dict.__getitem__(self, name) KeyError: 'a'
我应该在这做什么呢?
__getitem__
只在班上工作.您不能在实例的基础上覆盖它.
这有效:
class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() def __getitem__(self, item): return self.a[item] b1 = B() b1.a['a'] = 5 b2 = B() b2.a['b'] = 10 c = b1['a'] d = b2['b']
如果__init__
由于某些奇怪的原因想要定义它,则必须创建描述符:
def __init__(self): self.a = A() def mygetitem(self, item): return self.a[item] B.__getitem__ = types.MethodType(mygetitem, None, B)