Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python super() 함수는 다중 상속에서 어떻게 작동할까?

super() 함수를 본격적으로 살펴보기 전에, 먼저 다중 상속(Multiple Inheritance)이라는 개념부터 짚고 넘어갈 필요가 있습니다.

다중 상속이란?

다중 상속이란 하나의 자식 클래스가 둘 이상의 부모 클래스로부터 속성과 메서드를 상속받는 것을 의미합니다. Python은 이러한 다중 상속을 기본 문법으로 지원하는 대표적인 언어 중 하나입니다.

아래 예제에서 Child 클래스는 Father 클래스와 Mother 클래스 양쪽으로부터 속성과 메서드를 물려받습니다.

예제

class Father:
    fathername = ""
    def father(self):
        print(self.fathername)

class Mother:
    mothername = ""
    def mother(self):
        print(self.mothername)

class Child(Father, Mother):
    def parent(self):
        print("Father :", self.fathername)
        print("Mother :", self.mothername)

s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()

실행 결과

Father : Srinivas
Mother : Anjali

다중 상속에서 super()의 동작 방식

다음 예제는 다중 상속 환경에서 super()가 실제로 어떻게 작동하는지 보여줍니다.

super(): super 함수는 부모 클래스의 메서드를 클래스 이름으로 직접 명시하여 호출하는 것을 대체할 수 있습니다. 특히 __init__ 같은 초기화 메서드를 호출할 때 자식 클래스에서 부모 클래스 이름을 일일이 적지 않아도 되므로, 코드가 간결해지고 나중에 상속 구조가 바뀌어도 수정 범위를 최소화할 수 있다는 장점이 있습니다.

예제

class Father:
    fathername = ""
    def father(self):
        print(self.fathername)

class Mother:
    mothername = ""
    def mother(self):
        print(self.mothername)

class Child(Father, Mother):
    def parent(self):
        super().__init__()
        print("i am here")
        print("Father :", self.fathername)
        print("Mother :", self.mothername)

s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()

프로그램을 실행하면 아래와 같은 결과가 출력됩니다.

실행 결과

i am here
Father : Srinivas
Mother : Anjali

MRO(메서드 결정 순서) 이해하기

다중 상속에서 super()가 올바르게 작동하는 비결은 MRO(Method Resolution Order)에 있습니다. Python은 클래스에 정의된 부모 클래스의 순서를 기준으로 메서드 탐색 순서를 결정하며, super()는 단순히 '첫 번째 부모 클래스'만 가리키는 것이 아니라 MRO상에서 다음 클래스를 차례대로 찾아갑니다.

MRO는 다음과 같이 확인할 수 있습니다.

print(Child.__mro__)
# (<class 'Child'>, <class 'Father'>, <class 'Mother'>, <class 'object'>)

이처럼 super()를 활용하면 다중 상속 구조에서도 일관성 있고 유지보수하기 쉬운 객체 초기화 흐름을 만들 수 있습니다.