您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页super()和super().__init__()的解释

super()和super().__init__()的解释

来源:伴沃教育


一、super

1.基本概念

在python继承当中,super()函数主要用在子类中调用父类的方法。它返回一个特殊对象,这个对象会帮我们调用父类方法

     class Parent:
         def __init__(self, name):
             self.name = name
         def say_hello(self):
             print(f"Hello, I'm {self.name} from Parent.")
     class Child(Parent):
         def say_hello(self):
             super().say_hello()
             print("I'm also from Child.")
     child = Child("Alice")
     child.say_hello()

在中国例子中,Child类继承自Parent方法。在Child类的say_hello方法中,首先通过super().say_hello()调用了父类Parent的say_hello方法。然后再执行自己的代码,这样就实现了子类方法中先执行父类方法,再执行子类特有的行为

2.多继承中的方法解析顺序

MRO概念:当涉及多继承时,Python 使用一种称为方法解析顺序(Method Resolution Order,MRO)的机制来确定方法的调用顺序。super()会根据 MRO 来查找并调用合适的父类方法

     class A:
         def method(self):
             print("This is method from A")
     class B(A):
         def method(self):
             print("This is method from B")
             super().method()
     class C(A):
         def method(self):
             print("This is method from C")
             super().method()
     class D(B, C):
         def method(self):
             print("This is method from D")
             super().method()
     d = D()
     d.method()

在这里,D类继承自BCBC又都继承自A。当在D类的method方法中调用super().method()时,Python 会根据 MRO(在这种情况下是 D - B - C - A)来查找并调用下一个类中的method方法。首先打印This is method from D,然后根据 MRO,调用B类中的method方法,接着调用C类中的method方法,最后调用A类中的method方法。

二、super().__init__()方法

1.继承中的属性初始化

在子类的构造函数(__init__方法)中,super()可以用来初始化父类的属性。这确保了子类对象在继承父类属性的同时,能够正确地初始化这些属性。

     class Vehicle:
         def __init__(self, brand):
             self.brand = brand
     class Car(Vehicle):
         def __init__(self, brand, model):
             super().__init__(brand)
             self.model = model
     my_car = Car("Toyota", "Corolla")
     print(my_car.brand)  
     print(my_car.model)  

Car类的__init__方法中,通过super().__init__(brand)初始化了从Vehicle类继承的brand属性,然后又初始化了自己特有的model属性。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务