这是一个非常人为的示例,因为要解释我最终实施此解决方案的背景并不容易。但是,如果有人能回答为什么会发生这种特殊情况,我将不胜感激。
这个例子:
class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem'
return dict.__getitem__(name)
class B(object):
def __init__(self):
self._a = A()
setattr(self, '__getitem__', self._a.__getitem__)
b = B()
c = b['a']
这输出:
c = b['a']
TypeError: 'B' object is unsubscriptable
即使这是一种奇怪的方式(显然子类化会更合乎逻辑),为什么它找不到我明确设置的方法?
如果我这样做:
dir(b)
我明白了:
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a']
其他方法也会出现同样的问题,例如__iter__
. 明确定义这种有效的方法是什么?