重定向python中的函数定义

Dan*_*Dan 2 python class-attributes

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

这个例子:

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']
Run Code Online (Sandbox Code Playgroud)

这输出:

c = b['a']
TypeError: 'B' object is unsubscriptable
Run Code Online (Sandbox Code Playgroud)

即使这是一种奇怪的方式(显然子类化更合乎逻辑),为什么它找不到我明确设置的方法?

如果我这样做:

dir(b)
Run Code Online (Sandbox Code Playgroud)

我明白了:

['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a']
Run Code Online (Sandbox Code Playgroud)

其他方法也会出现同样的问题__iter__.明确定义这个有效的方法是什么意思?

nos*_*klo 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']
Run Code Online (Sandbox Code Playgroud)