Nâng CaoPython iconPython

MRO (Method Resolution Order) là gì? Python giải quyết diamond problem thế nào?

MRO xác định thứ tự Python tìm method trong cây kế thừa, dùng thuật toán C3 Linearization.

Giải quyết diamond problem bằng cách đảm bảo mỗi class chỉ xuất hiện một lần.

python
class A:
    def method(self): print("A")

class B(A):
    def method(self): super().method(); print("B")

class C(A):
    def method(self): super().method(); print("C")

class D(B, C): pass

D().method()   # A → C → B (theo MRO)
print(D.__mro__)  # D, B, C, A, object

Xem MRO: ClassName.__mro__ hoặc ClassName.mro().

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python