2

这是一个非常人为的示例,因为要解释我最终实施此解决方案的背景并不容易。但是,如果有人能回答为什么会发生这种特殊情况,我将不胜感激。

这个例子:

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__. 明确定义这种有效的方法是什么?

4

2 回答 2

7

当您使用方括号时,[]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']
于 2009-03-25T18:29:16.493 回答
1

这是因为您不能即时覆盖特殊的类方法。

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

于 2009-03-25T18:19:25.877 回答