[파이썬] 다중 상속과 메서드 해상도 순서

소개

파이썬은 여러 클래스를 동시에 상속 받을 수 있는 다중 상속을 지원합니다. 하지만 다중 상속을 사용할 때 주의해야 할 것 중 하나는 메서드 해상도 순서입니다. 메서드 해상도 순서는 다중 상속을 사용할 때 어떤 부모 클래스의 메서드가 호출되는지 결정하는 규칙을 의미합니다.

다중 상속 예시

class Parent1:
    def greet(self):
        return "Hello from Parent 1"

class Parent2:
    def greet(self):
        return "Hello from Parent 2"

class Child(Parent1, Parent2):
    pass

child = Child()
print(child.greet())  # 출력: "Hello from Parent 1"

위의 예시에서 Child 클래스는 Parent1 클래스와 Parent2 클래스를 다중 상속 받습니다. 하지만 Child 클래스의 인스턴스인 child에서 greet() 메서드를 호출하면 "Hello from Parent 1"이 출력됩니다. 이는 메서드 해상도 순서 때문에 발생하는 현상입니다.

메서드 해상도 순서 (Method Resolution Order)

파이썬은 C3 선형화라는 알고리즘을 사용하여 메서드 해상도 순서를 결정합니다. C3 선형화 알고리즘은 부모 클래스의 목록을 순서대로 조합하여 메서드를 해상도하는 규칙입니다.

만약 위 예시에서 Child 클래스를 다음과 같이 수정하면 어떻게 될까요?

class Parent1:
    def greet(self):
        return "Hello from Parent 1"

class Parent2:
    def greet(self):
        return "Hello from Parent 2"

class Child(Parent2, Parent1):
    pass

child = Child()
print(child.greet())  # 출력: "Hello from Parent 2"

위의 코드에서 Child 클래스에서 Parent2Parent1의 순서가 바뀌었습니다. 이 경우 Child 클래스의 인스턴스인 child에서 greet() 메서드를 호출하면 "Hello from Parent 2"가 출력됩니다.

super() 함수 사용

메서드 해상도 순서를 변경하는 것이 아니라 모든 부모 클래스의 메서드를 호출하고 싶은 경우 super() 함수를 사용할 수 있습니다. super() 함수는 현재 클래스의 부모 클래스를 차례로 호출하는 역할을 합니다.

class Parent1:
    def greet(self):
        return "Hello from Parent 1"

class Parent2:
    def greet(self):
        return "Hello from Parent 2"

class Child(Parent1, Parent2):
    def greet(self):
        return super().greet()  # 부모 클래스의 greet() 메서드 호출

child = Child()
print(child.greet())  # 출력: "Hello from Parent 1"

위의 예시에서 Child 클래스의 greet() 메서드는 super().greet()를 호출하고 있습니다. 따라서 Child 클래스의 인스턴스에서 greet() 메서드를 호출하면 Parent1 클래스의 greet() 메서드가 호출됩니다.

결론

다중 상속을 사용할 때는 메서드 해상도 순서를 이해하고 적절히 처리하는 것이 중요합니다. 메서드 해상도 순서를 변경하기 위해 super() 함수를 사용하거나 원하는 부모 클래스의 메서드를 직접 호출할 수 있습니다. 다중 상속을 올바르게 사용하면 코드 재사용성을 높일 수 있으나, 메서드 해상도 순서에 대한 이해가 필요합니다.