Kế thừa là khái niệm trong đó một lớp truy cập các phương thức và thuộc tính của một lớp khác.
- Lớp cha là lớp được kế thừa từ đó, còn được gọi là lớp cơ sở.
- Lớp con là lớp kế thừa từ một lớp khác, còn được gọi là lớp dẫn xuất.
Có hai kiểu kế thừa trong python -
- Thừa kế Nhiều tài sản
- Kế thừa Đa cấp
Nhiều người thừa kế -
Trong đa kế thừa, một lớp con có thể kế thừa nhiều lớp cha.
Ví dụ
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() Đầu ra
Father : Srinivas Mother : Anjali
Kế thừa đa cấp
Trong kiểu kế thừa này, một lớp có thể kế thừa từ một lớp con / lớp dẫn xuất.
Ví dụ
#Daughter class inherited from Father and Mother classes which derived from Family class.
class Family:
def family(self):
print("This is My family:")
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() Đầu ra
This is My family: Father : Srinivas Mother : Anjali