【问题标题】:Is it necessary to call super().__init__() explicitly in python?是否有必要在 python 中显式调用 super().__init__() ?
【发布时间】:2020-05-17 19:08:55
【问题描述】:

我来自 Java,我们可以避免调用超类零参数构造函数。对它的调用由编译器隐式生成。

我阅读了this post about super(),现在质疑是否真的有必要明确地做这样的事情:

class A(object):
 def __init__(self):
   print("world")

class B(A):
 def __init__(self):
   print("hello")
   super().__init__() #Do we get some Undefined Behavior if we do not call it explicitly?

【问题讨论】:

  • 如果省略“world”会打印吗?
  • @Sayse 问题不在于特定 python 实现的行为。总的来说,这是关于合法性。
  • 是的,但无论是否打印,答案都应该很清楚
  • 世界没有被打印出来..example
  • 省略 super init 不是 UB,就像省略任何其他调用一样。对象在初始化之前就已经定义好了。

标签: python python-3.x class inheritance constructor


【解决方案1】:

如果你重写超类的__init__ 方法,那么子类的__init__ 方法需要显式调用它,如果这是预期的行为,是的。

__init__的心智模型不正确;它不是构造方法,它是构造方法调用的一个钩子,可以让您轻松自定义对象初始化。 (实际的构造函数称为__new__,但您不需要知道这一点,并且可能永远不需要直接与其交互,更不用说更改它了。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2015-12-09
    • 2020-11-06
    • 2017-06-30
    • 2011-04-01
    • 2023-04-04
    • 2015-02-18
    相关资源
    最近更新 更多