第25条 用super初始化父类

在Python中初始化父类的方法,是在子类继承的构造函数中调用父类的init方法。

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
 
class Student(Person):
    def __init__(self,name,age,score):
        Person.__init__(self,name,age)
        self.score = score

在简单的继承体系中,可以使用上述方法,但是对于复杂的继承,上述初始化父类的方法,会带来无法预知的行为错误。

影响1:调用顺序由子类中的__init__方法中的顺序指定;
影响2:对于菱形继承,会导致公共的基类的__init__方法执行多次,从而产生错误。

菱形继承
在这里插入图片描述

因此在Python中总是使用super函数来初始化父类。


class A(object):
  def __init__(self):
        print('enter A')
        print('leave A')
        
class B(A):
    def __init__(self):
        print('enter B')
        super().__init__()
        print('leave B')

class C(A):
    def __init__(self):
        print('enter C')
        super().__init__()
        print('leave C')

class D(B, C):
    def __init__(self):
        print('enter D')
        super().__init__()
        print('leave D')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章