python - 在 python 中重定向函数定义

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

这个输出:

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/

相关文章:

python - 我陷入了从矩阵检索值的过程

python - matplotlib opencv 图像子图

python - 更新我的类和创建 Sprite 的方式后,移动的功能不再起作用

python - 动态创建类属性

无法正确识别实例列表中的 Python 类属性

python - 是否可以在 Apache 服务器上下文之外运行 mod_python Python 服务器页面?

python - 在 C 中嵌入 Python : Passing a two dimensional array and retrieving back a list

.net - 自定义 .NET 属性的实际使用

python - Python 中的抽象类属性?