【问题标题】:Why it is compulsory to give classname while using super() in Python [duplicate]为什么在 Python 中使用 super() 时必须提供类名 [重复]
【发布时间】:2012-09-25 13:08:39
【问题描述】:

可能重复:
Why do I have to specify my own class when using super(), and is there a way to get around it?

我正在阅读这本书 - "Core Python Programming",我真的觉得它非常好。但是我在研究继承主题时有一段时间感到困惑..

某处的书说-我们可以使用super() 调用super class method,这将为我们找到基类方法,而且我们不需要显式传递self,就像我们没有super..

下面是示例代码:-

# Invoking super class method without super() .. Need to pass `self` as argument
class Child(Parent):
    def foo(self):
        Parent.foo(self)

# Invoking with super().
# No need to pass `self` as argument to foo()
class Child(Parent1, Parent2):
    def foo(self):
        super(Child, self).foo()
        print 'Hi, I am Child-foo()'

我的问题是 - 为什么我们必须将 classname 传递给 super() 调用.. 因为可以从调用 super 的类中推断出类名..

所以,由于 super() 是从 class Child,类名应该是隐含的。那我们为什么需要它??

*EDIT: - 将Child 作为参数提供给 super() 没有意义,因为它没有提供任何信息.. 我们可以使用 super(self).. 并且该方法会被搜索在超类中按照括号内给出的顺序..

【问题讨论】:

标签: python python-2.7


【解决方案1】:

通过提供类名作为第一个参数,您提供了冗余信息。是的。这有点愚蠢*,这就是为什么 super 的行为在 Python 3 中发生了变化。

*我的回答实际上与约翰卡特的回答相矛盾。当然,只有我们中的一个人是对的。我不想冒犯他和其他人,我很高兴看到一个有意义的例子,其中super(C, self).method(arg) 并没有在C 类中实际使用:-)。

【讨论】:

  • 谢谢 Jan... 我使用的是 Python 2.7。它的行为完全不同..
  • 你说得对,Jan。我撤回了最初的答案,没有冒犯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多