国外注册品牌 建设网站,石狮外贸网站建设公司报价,如何建单页网站栏目,比较好的家装设计网站一、super 
1.基本概念 
在python继承当中#xff0c;super()函数主要用在子类中调用父类的方法。它返回一个特殊对象#xff0c;这个对象会帮我们调用父类方法 class Parent:def __init__(self, name):self.name  namedef say_hello(self):print(fHello, Im {self.nam…一、super 
1.基本概念 
在python继承当中super()函数主要用在子类中调用父类的方法。它返回一个特殊对象这个对象会帮我们调用父类方法 class Parent:def __init__(self, name):self.name  namedef say_hello(self):print(fHello, Im {self.name} from Parent.)class Child(Parent):def say_hello(self):super().say_hello()print(Im 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 OrderMRO的机制来确定方法的调用顺序。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类继承自B和CB和C又都继承自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  brandclass Car(Vehicle):def __init__(self, brand, model):super().__init__(brand)self.model  modelmy_car  Car(Toyota, Corolla)print(my_car.brand)  print(my_car.model)   
在Car类的__init__方法中通过super().__init__(brand)初始化了从Vehicle类继承的brand属性然后又初始化了自己特有的model属性。