在类中调用父类的 __call__ 方法

Posted

技术标签:

【中文标题】在类中调用父类的 __call__ 方法【英文标题】:Calling parent's __call__ method within class 【发布时间】:2011-12-10 00:47:12 【问题描述】:

我想从继承的类中调用父级的 call 方法

代码如下所示

#!/usr/bin/env python

class Parent(object):

    def __call__(self, name):
        print "hello world, ", name


class Person(Parent):

    def __call__(self, someinfo):                                                                                                                                                            
        super(Parent, self).__call__(someinfo)

p = Person()
p("info")

我明白了,

File "./test.py", line 12, in __call__
super(Parent, self).__call__(someinfo)
AttributeError: 'super' object has no attribute '__call__'

我不知道为什么,有人可以帮我解决这个问题吗?

【问题讨论】:

【参考方案1】:

super 函数将 派生的 类作为其第一个参数,而不是基类。

super(Person, self).__call__(someinfo)

如果你需要使用基类,你可以直接做(但要注意这会破坏多重继承,所以你不应该这样做,除非你确定这是你想要的):

Parent.__call__(self, someinfo)

【讨论】:

您能否解释一下为什么 super()() 没有明确的 __call__ 对于未来的谷歌员工来说会失败?哦,提出新问题的懒惰:-) super() 实例代理属性访问,但the call operation doesn't look up the __call__ attribute on the instance。 (这里提到了in super() docs,但那里的语言相当技术性……)

以上是关于在类中调用父类的 __call__ 方法的主要内容,如果未能解决你的问题,请参考以下文章

继承问题:

类的成员,类的特殊方法

类的三大方法 与__init___

Python3中__call__方法介绍

Day 5-8 自定义元类控制类的实例化行为

父类中的方法被覆盖以及子类调用父类覆盖的方法