这是一个非常人为的例子,因为它不容易解释我最终实现这个解决方案的背景。但是,如果有人能回答为什么会出现这种特殊情况,我将不胜感激。
例子:
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__
。明确定义这种有效的方法有什么意义?
最佳答案
当你使用方括号时 []
python 在类中查找。您必须在类中设置该方法。
这里是你的代码改编:
class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem!'
return dict.__getitem__(self, name)
class B(object):
def __init__(self):
self._a = A()
B.__getitem__ = self._a.__getitem__
b = B()
c = b['a']
关于python - 在 python 中重定向函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/682822/