【发布时间】: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