python 多继承super,python 父类方法用super

  python 多继承super,python 父类方法用super

  本文介绍了目录Python中的单类继承、公共类方法继承、初始化函数继承、Python中的多类继承

  Python中的单个类继承

  Python是一种支持类继承的面向对象编程语言。新类称为子类,继承的类称为父类、基类或超类。子类继承了父类之后,就拥有了父类的所有特征。一个简单的类继承的例子:

  普通方法继承class fruit():def color(self):print( colorful )class Apple(fruit):passclassorange(fruit):pass Apple=Apple()orange=orange()Apple。Color()orange . color()# output # colorly # colorly这里水果是父类,Apple和Orange是子类,继承了父类的特性,所以Apple和Orange也有color方法。

  除了继承父类的方法,子类还可以覆盖父类的方法:

  类Fruit():def color(self):print( colorful )类Apple(Fruit):def color(self):print( red )类Orange(Fruit):def color(self):print( Orange )Apple=Apple()Orange=Orange()Apple . color()Orange . color()# output # red # Orange子类可以在继承父类的方法的同时重构方法。这样,子类的方法既包含了父方法的特点,也包含了子类本身的特点:

  类水果():def color(self): print(水果五颜六色)类苹果(Fruit): def color(self): super()。color() print(苹果是红的)Class orange(水果):def color(自身):super()。color()print( orange is orange )apple=apple()orange=orange()apple . color()orange . color()# output #水果五颜六色# appleisred #水果五颜六色# orange is orange初始化函数继承如果需要传入参数给类,就需要使用初始化函数。如果所有子类中的某些参数是相同的,那么可以在父类的初始化函数中定义这些参数,然后子类继承父类的初始化函数,这样所有子类就可以共享这些参数,而不用在每个子类中单独定义。初始化函数的继承:

  类水果():def __init__(self,color,shape):self . color=color self . shape=shape class苹果(水果):def __init__(self,color,shape,Taste):水果。_ _ init _ _ (self,color,shape) #相当于super()。_ _ init _ _(颜色,形状)自我。taste=tastedef feature(self):print(苹果的颜色是{},形状是{},味道是{} 。format( self.color,self.shape,self.taste))类橙(水果):def __init__(self,color,shape,taste):水果。__init__(self,color,shape)self . taste=taste def feature(self):print(橙子的颜色是{},形状是{},味道是{})。format( self.color,self.shape,self.taste))apple=Apple(red , square , sour)orange=Orange(orange , round ,Sweet )Apple . feature()Orange . feature()# output # Apple的颜色是红色,形状是方形,味道是酸味# orange的颜色是橙色,形状是圆形中的多类继承,味道是单类继承中的甜味Python,super()函数用来指向要继承的父类,不需要显式写出父类的名称。但是在多类继承中,会涉及到搜索顺序(MRO)和钻石继承等问题。MRO是一个类的方法解析序列表,也就是继承父类方法时的序列表。钻石传承:

  A/\ B C \/D如图,A是父类,B和C继承A,D继承B和C,下面是钻石继承的继承顺序示例:

  class Plant():def _ _ init _ _(self):print( Enter Plant )print( Leave Plant )class Fruit(Plant):def _ _ init _ _(self):print( Enter Fruit )super().__init__() print(留果)类蔬菜(植物):def __init__(self): print(进菜)super().__init__() print(离开蔬菜)类番茄(水果,蔬菜):def __init__(self): print(进入番茄)super()._ _ init _ _()print( Leave Tomato )Tomato=Tomato()print(Tomato .__mro__)#输出#输入番茄#输入水果#输入蔬菜#输入植物#离开植物#离开蔬菜#离开水果#离开番茄# (class __main__ .番茄,主要成分。水果,class __main__ .蔬菜类主要是。植物,类对象)

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: