继承 是一个类访问另一个类的方法和属性的概念。
父类是从其继承的类,也称为基类。
子类是从另一个类(也称为派生类)继承的类。
python中有两种继承类型:
多重继承
多级继承
在多重继承中,一个子类可以继承多个父类。
class Father: fathername = "" def father(self): print(self.fathername) class Mother: mothername = "" def mother(self): print(self.mothername) class Daughter(Father, Mother): def parent(self): print("Father :", self.fathername) print("Mother :", self.mothername) s1 = Daughter()s1.fathername = "Srinivas" s1.mothername = "Anjali" s1.parent()
输出结果
Father : Srinivas Mother : Anjali
在这种继承类型中,类可以从子类/派生类继承。
#Daughter class inherited from Father and Mother classes which derived from Family class. class Family: def family(self): print("这是我的家人:") class Father(Family): fathername = "" def father(self): print(self.fathername) class Mother(Family): mothername = "" def mother(self): print(self.mothername) class Daughter(Father, Mother): def parent(self): print("Father :", self.fathername) print("Mother :", self.mothername) s1 = Daughter()s1.fathername = "Srinivas" s1.mothername = "Anjali" s1.family() s1.parent()
输出结果
这是我的家人: Father : Srinivas Mother : Anjali