PYTHON · 객체지향
다중 상속과 MRO
Python의 다중 상속에서 메서드 호출 순서(MRO)는 C3 선형화 알고리즘으로 결정됩니다.
객체지향고급MRO다중 상속superC3 선형화
핵심 설명
Python의 다중 상속에서 메서드 호출 순서(MRO)는 C3 선형화 알고리즘으로 결정됩니다.
Python code
class A:
def greet(self):
return "A"
class B(A):
def greet(self):
return "B → " + super().greet()
class C(A):
def greet(self):
return "C → " + super().greet()
class D(B, C):
def greet(self):
return "D → " + super().greet()
d = D()
print(d.greet()) # D → B → C → A
# MRO 확인
print(D.__mro__)
# (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)
# super()는 MRO를 따라 다음 클래스를 호출
for cls in D.__mro__:
print(f" {cls.__name__}", end="")
print()
# 다이아몬드 문제 해결
class Base:
def __init__(self):
print("Base.__init__")
class Left(Base):
def __init__(self):
super().__init__()
print("Left.__init__")
class Right(Base):
def __init__(self):
super().__init__()
print("Right.__init__")
class Child(Left, Right):
def __init__(self):
super().__init__()
print("Child.__init__")
Child() # Base, Right, Left, Child (각 1회만)학습 팁
super()는 현재 클래스가 아닌 MRO에서 다음 클래스를 호출합니다. 다중 상속에서 super()를 일관되게 사용하세요.
주의할 점
다중 상속 시 super().__init__()을 빠뜨리면 MRO 체인이 끊어져 일부 부모 클래스가 초기화되지 않습니다.
자주 묻는 질문
다중 상속과 MRO란 무엇인가요?
Python의 다중 상속에서 메서드 호출 순서(MRO)는 C3 선형화 알고리즘으로 결정됩니다.
다중 상속과 MRO 학습 시 주의할 점은 무엇인가요?
다중 상속 시 super().__init__() 을 빠뜨리면 MRO 체인이 끊어져 일부 부모 클래스가 초기화되지 않습니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.