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

파이썬 상속의 종류: 다중 상속과 다단계 상속 쉽게 이해하기

상속(Inheritance)은 하나의 클래스가 다른 클래스의 메서드와 속성에 접근하여 사용할 수 있도록 하는 객체 지향 프로그래밍의 핵심 개념입니다.

  • 부모 클래스(Parent Class): 상속을 제공하는 클래스로, 기반 클래스(Base Class)라고도 부릅니다.
  • 자식 클래스(Child Class): 다른 클래스로부터 상속을 받는 클래스로, 파생 클래스(Derived Class)라고도 부릅니다.

파이썬에서는 크게 두 가지 유형의 상속을 사용할 수 있습니다.

  • 다중 상속(Multiple Inheritance)
  • 다단계 상속(Multilevel Inheritance)

1. 다중 상속(Multiple Inheritance)

다중 상속은 하나의 자식 클래스가 둘 이상의 부모 클래스로부터 동시에 상속받는 방식입니다. 아래 예제에서는 Daughter 클래스가 FatherMother라는 두 개의 부모 클래스를 모두 상속받습니다.

예제 코드

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

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

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

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

실행 결과

Father : Srinivas
Mother : Anjali

2. 다단계 상속(Multilevel Inheritance)

다단계 상속은 한 클래스가 이미 다른 클래스를 상속받은 파생 클래스(자식 클래스)를 다시 상속하는 형태입니다. 즉, 조상 클래스 → 부모 클래스 → 자식 클래스처럼 상속 관계가 여러 단계로 이어집니다.

아래 예제에서는 Family 클래스를 기반으로 FatherMother 클래스가 상속받고, 이들을 다시 Daughter 클래스가 상속받아 최종적으로 조상 클래스의 기능까지 함께 사용할 수 있습니다.

예제 코드

# Family 클래스를 상속받은 Father, Mother 클래스를
# Daughter 클래스가 다시 상속하는 다단계 상속 구조입니다.
class Family:
    def family(self):
        print("This is My family:")

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

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

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

s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.family()
s1.parent()

실행 결과

This is My family:
Father : Srinivas
Mother : Anjali

정리

파이썬의 상속은 코드 재사용성을 높이고 클래스 간의 계층 구조를 명확하게 만들어 줍니다. 다중 상속은 여러 부모 클래스의 기능을 한 번에 물려받을 때, 다단계 상속은 상속 관계를 여러 단계로 확장하고 싶을 때 활용하면 효과적입니다.