Python教程: super()函数

super() 函数是 Python 中用于调用父类(超类)的方法的一个内置函数。它主要用于多重继承的场合,以确保父类被正确地调用,即使继承链变得复杂。super() 函数返回了一个代表父类的临时对象,通过这个对象可以调用父类中定义的方法。

基本用法
在子类的方法中,使用 super() 调用父类的方法的基本形式如下:

class Parent:  
    def __init__(self, value):  
        self.value = value  
        print(f"Parent initialized with {
      
      value}")  
  
class Child(Parent):  
    def __init__(self, value, extra):  
        super().__init__(value)  # 调用父类的构造函数  
        self.extra = extra  
        print(f"Child initialized with extra {
      
      extra}")  
  
# 使用子类  
child_instance = Child(10, "some extra info")

在这个例子中,Child 类的构造函数调用了 super().init(value),这实际上调用了 Parent 类的构造函数。

在方法中使用
super() 也可以在类的方法中使用,以调用父类中的方法:

class Parent:  
    def show(self):  
        print("Parent show() method")  
  
class Child(Parent):  
    def show(self):  
        super().show()  # 调用父类的 show() 方法  
        print("Child show() method")  
  
# 使用子类  
child_instance = Child()  
child_instance.show()

输出将是:

Parent show() method  
Child show() method

多重继承
在多重继承的情况下,super() 的行为更加复杂,但它仍然能够确保每个父类的方法只被调用一次(遵循方法解析顺序,MRO)。

class Base:  
    def __init__(self):  
        print("Base initialized")  
  
class Left(Base):  
    def __init__(self):  
        super().__init__()  
        print("Left initialized")  
  
class Right(Base):  
    def __init__(self):  
        super().__init__()  
        print("Right initialized")  
  
class Bottom(Left, Right):  
    def __init__(self):  
        super().__init__()  
        print("Bottom initialized")  
  
# 使用 Bottom 类  
bottom_instance = Bottom()
输出将是:

Base initialized  
Left initialized  
Right initialized  
Bottom initialized

在这个例子中,Bottom 类同时继承自 Left 和 Right,而 Left 和 Right 都继承自 Base。super() 函数确保了 Base 的构造函数只被调用一次,并且按照 MRO 的顺序调用每个类的构造函数。

总结
super() 用于调用父类(超类)的方法。
在单继承中,super() 简单地调用直接父类的方法。
在多重继承中,super() 根据方法解析顺序(MRO)调用父类的方法,确保每个父类的方法只被调用一次。
super() 常用于初始化方法(init),但也可以用于调用其他父类方法。
使用 super() 可以使代码更加清晰和易于维护,特别是在涉及多重继承的复杂继承体系中。

猜你喜欢

转载自blog.csdn.net/m0_65482549/article/details/143162451