在类中调用父类的__call__方法

10

我想要从继承类中调用父类的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个回答

18
< p > super函数的第一个参数应该是派生类而不是基类。< /p >
super(Person, self).__call__(someinfo)

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

Parent.__call__(self, someinfo)

4
你能否解释为什么在没有显式定义__call__的情况下,使用super()()会失败,以便于未来的搜索者能够理解?哦,我这样偷懒提出新问题 :-) - Ciro Santilli OurBigBook.com
2
super()实例代理属性访问,但调用操作不会在实例上查找__call__属性。(这在super()文档中提到,但那里的语言非常技术化...) - Petr Viktorin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接