本人CSDN博客专栏:https://blog.csdn.net/yty_7
Github地址:https://github.com/yot777/Python-Primary-Learning
8.4 多继承
Python的类可以继承自多个父类,叫多继承。
多继承的语法:
class ClassName(Base1, Base2, Base3):
注意圆括号中父类的顺序。若是父类中有相同的方法名,而在子类使用时未指定,Python将从左到右查找父类中是否包含方法。
Java不支持多继承,但Java有类似的概念叫接口(interface),可以用多个类来实现(implements)该接口。
Python多继承程序举例:
class Student():
name =''
age =0
grade =''
def __init__(self,n,a,g):
self.name = n
self.age = a
self.grade = g
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
class Speaker():
topic =''
name =''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我演讲的主题是 %s"%(self.name,self.topic))
#多重继承
class Sample(Student,Speaker):
def __init__(self,n,a,g,t):
Student.__init__(self,n,a,g)
Speaker.__init__(self,n,t)
person = Sample("Tim",10,4,"Python")
#方法名相同,默认调用的是在括号中排前的父类的方法
person.speak()
运行结果:
Tim 说: 我 10 岁了,我在读 4 年级
请注意多继承的顺序,下面用图表来展示:
Python多继承顺序1:
class Sample(Student,Speaker):
def __init__(self,n,a,g,t):
Student.__init__(self,n,a,g)
Speaker.__init__(self,n,t)
person = Sample("Tim",10,4,"Python")
person.speak()
解析:class Sample(Student,Speaker): 表示Sample类继承自Student类和Speaker类,若是父类中有相同的方法名,而在子类使用时未指定,Python将从左到右查找父类中是否包含方法:先查找Student类的方法,再查找Speaker类的方法。
Python多继承顺序2:
class Sample(Speaker,Student):
def __init__(self,n,a,g,t):
Student.__init__(self,n,a,g)
Speaker.__init__(self,n,t)
person = Sample("Tim",10,4,"Python")
person.speak()
解析:class Sample(Speaker,Student): 表示Sample类继承自Speaker类和Student类,若是父类中有相同的方法名,而在子类使用时未指定,Python将从左到右查找父类中是否包含方法:先查找Speaker类的方法,再查找Student类的方法。
参考教程:
廖雪峰的Python教程
https://www.liaoxuefeng.com/wiki/1016959663602400
廖雪峰的Java教程
https://www.liaoxuefeng.com/wiki/1252599548343744
Python3 教程 | 菜鸟教程
https://www.runoob.com/python3/
如果您觉得本篇本章对您有所帮助,欢迎关注、评论、点赞!Github欢迎您的Follow、Star!