【发布时间】:2020-03-17 18:47:49
【问题描述】:
我想知道为什么在 Python 中,派生类必须调用其基类的构造函数才能继承所有实例属性。
例如:
class A:
def __init__(self):
self.a = 0
class B(A):
def __init__(self):
super().__init__() # this is mandatory in order to inherit A's instance attributes
self.b = 1
a = A()
b = B()
print(b.a) # this gives an error it the line super().__init__() is omitted
但是,在其他编程语言中,调用基类构造函数是不必要的。
【问题讨论】:
-
因为与其他语言不同,python类变量都是在构造函数中定义和初始化的
-
子类覆盖
__init__()而不是从父类继承它,因此它需要一种方式来表示“去做我父母的__init__()会做的所有事情。”
标签: python inheritance