在类中调用父类的__call__方法

10 投票
1 回答
8578 浏览
提问于 2025-04-17 04:33

我想在一个继承的类里调用父类的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

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

super(Person, self).__call__(someinfo)

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

Parent.__call__(self, someinfo)

撰写回答