这是一个非常人为的例子,因为它不容易解释中,我已经结束了执行本解决方案的上下文。但是,如果任何人都可以回答为什么这个特殊的特点发生了,我会很感激。

的示例:

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__发生同样的问题。是什么样的明确定义这种方法的作品?

有帮助吗?

解决方案

当您使用括号的 [] 的蟒蛇看起来类。必须设置在类中的方法。

这是你的代码调整:

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']

其他提示

这是因为你不能覆盖在飞行中的特殊类的方法。

我无法找到关于此参考,但基本上是因为它们是类方法和不允许为实例方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top