Có, Python hỗ trợ đa kế thừa (multiple inheritance): một lớp con có thể kế thừa từ nhiều lớp cha.
Ví dụ cơ bản
class Animal:
def eat(self):
print("It eats insects.")
def sleep(self):
print("It sleeps in the night.")
class Bird(Animal):
def fly(self):
print("It flies in the sky.")
def sing(self):
print("It sings a song.")
# Kiểm tra quan hệ kế thừa
print(issubclass(Bird, Animal)) # True
koyal = Bird()
print(isinstance(koyal, Bird)) # True
koyal.eat()
koyal.sleep()
koyal.fly()
koyal.sing()
True True It eats insects. It sleeps in the night. It flies in the sky. It sings a song.
Trong ví dụ này: Bird chỉ kế thừa từ Animal (đơn kế thừa). Đa kế thừa thực sự là lớp con kế thừa từ 2+ lớp cha độc lập.
Ví dụ đa kế thừa thực sự
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Child(Father, Mother): # Kế thừa từ CẢ HAI
def parents(self):
print("Father:", self.fathername)
print("Mother:", self.mothername)
s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parents()
Father: Srinivas Mother: Anjali
MRO (Method Resolution Order) - Thứ tự ưu tiên
Python dùng thuật toán C3 Linearization. Xem MRO:
print(Child.__mro__)
(, , , )
Khi gọi super(), Python tuân theo MRO này.
Diamond Problem (Vấn đề kim cương)
class A:
def show(self): print("A")
class B(A):
def show(self): print("B")
class C(A):
def show(self): print("C")
class D(B, C):
pass
d = D()
d.show() # Gọi theo MRO: D -> B -> C -> A
B
D.__mro__: D -> B -> C -> A -> object. Phương thức show() của B được gọi vì B đứng trước C trong MRO.
Best Practice
- Sử dụng
super()để gọi phương thức cha theo MRO. - Tránh đa kế thừa phức tạp không cần thiết; ưu tiên composition (kết hợp).
- Hiểu MRO để debug dễ dàng.