Kế thừa (Inheritance) là cơ chế một lớp (child/derived) truy cập phương thức và thuộc tính của lớp khác (parent/base).
Python hỗ trợ 2 loại chính:
- Multiple Inheritance (Đa kế thừa)
- Multilevel Inheritance (Kế thừa nhiều cấp)
Lưu ý: Single inheritance (đơn kế thừa) là trường hợp cơ bản của multilevel (1 cấp).
1. Multiple Inheritance (Đa kế thừa)
Một lớp con kế thừa từ nhiều lớp cha cùng cấp.
Ví dụ
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Daughter(Father, Mother): # Kế thừa từ Father VÀ 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
2. Multilevel Inheritance (Kế thừa nhiều cấp)
Lớp con kế thừa từ lớp cha, mà lớp cha đó lại kế thừa từ lớp ông/bà (chuỗi kế thừa).
Ví dụ
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): # Kế thừa từ Father VÀ Mother (cả 2 đều kế thừa Family)
def parent(self):
print("Father:", self.fathername)
print("Mother:", self.mothername)
s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.family() # Từ Family (qua Father hoặc Mother)
s1.parent()
This is My family: Father: Srinivas Mother: Anjali
Sơ đồ: Family -> Father -> Daughter và Family -> Mother -> Daughter. Đây là đa kế thừa kết hợp kế thừa nhiều cấp (Diamond shape).
So sánh
| Loại | Mô tả | Số lớp cha trực tiếp |
|---|---|---|
| Single | 1 lớp con <- 1 lớp cha | 1 |
| Multiple | 1 lớp con <- nhiều lớp cha | >=2 |
| Multilevel | Grandparent -> Parent -> Child | 1 (mỗi cấp) |
| Hierarchical | 1 lớp cha -> nhiều lớp con | 1 |
| Hybrid | Kết hợp các loại trên | Phức hợp |
Lưu ý
Python không hỗ trợ private/protected members như Java/C++. Tất cả thuộc tính đều public (convention: _name protected, __name name mangling).