在类中调用parent的__call__方法

Jan*_*cak 8 python methods inheritance superclass

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

代码看起来像这样

#!/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")
Run Code Online (Sandbox Code Playgroud)

我明白了,

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

我无法弄清楚为什么,有人可以帮我这个吗?

Pet*_*rin 15

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

super(Person, self).__call__(someinfo)
Run Code Online (Sandbox Code Playgroud)

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

Parent.__call__(self, someinfo)
Run Code Online (Sandbox Code Playgroud)

  • 你能解释一下为什么没有明确的 `__call__` 的 `super()()` 对未来的谷歌员工来说会失败吗?哦,问新问题的懒惰:-) (3认同)
  • `super()` 实例代理属性访问,但是[调用操作不会查找实例上的 `__call__` 属性](https://docs.python.org/3/reference/datamodel.html#special-方法查找)。([在`super()`文档中提到了这一点](https://docs.python.org/3.5/library/functions.html#super),但是那里的语言相当技术性......) (2认同)