Python의 다중 상속

Ishaan Shrivastava 2021년7월10일
Python의 다중 상속

상속은 우리가 자식 클래스에서 부모 클래스 기능을 사용할 수있게 해주 며 객체 지향 프로그래밍의 필수 기능입니다. 상위 클래스에서 하위 클래스로의 데이터 재사용 및 전이성을 돕고 데이터 손실을 보상합니다.

다중 상속은 자식 클래스가 둘 이상의 부모 클래스에서 메서드와 기능을 상속하는 경우입니다. 한 번에 모든 데이터를 파생하는 것이 좋습니다. 그러나 다른 한편으로는 사용 복잡성과 모호성이 동반됩니다. 여러 부모가 동일한 기능을 소유하고있는 경우 어떤 기능이 어느 부모에서 왔는지 알기가 모호합니다. 다중 상속이 올바르게 사용되지 않거나 구현되지 않았을 때 발생합니다. 가상 상속, MRO (Method Resolution Order) 및super()함수를 사용하면 위험을 줄일 수 있습니다.

다음 코드에서 다중 상속의 기본 예를 볼 수 있습니다.

class Father:
    def drive(self):
        print("Father drives his son to school")


class Mother:
    def cook(self):
        print("Mother loves to cook for her son")


class Son(Father, Mother):
    def love(self):
        print("I love my Parents")


c = Son()
c.drive()
c.cook()
c.love()

출력:

Father drives his son to school
Mother loves to cook for her son
I love my parents

하위 클래스Son은 상위 클래스FatherMother에서 파생되어drive()cook()함수를 사용하여 원하는 출력을 제공 할 수 있습니다.

super()함수는 상속 된 자식 클래스의 부모 또는 형제 클래스를 참조하고 자식 클래스가 모든 수퍼 클래스 메서드를 사용할 수 있도록하는 임시 객체를 반환합니다.

이것은 일반적으로 상속이 경로를 건너기 시작할 때, 즉 두 부모 클래스가 수퍼 기본 클래스에서 파생 될 때 모호한 경우에 수행됩니다.

예를 들어

class Animals:
    def __init__(self, animalsName):
        print(animalsName, "is an animal.")


class Mammal(Animals):
    def __init__(self, Name):
        print(Name, "is a mammal.")
        super().__init__(Name)


class donotFly(Mammal):
    def __init__(self, name):
        print(name, "cannot fly.")
        super().__init__(name)


class donotSwim(Mammal):
    def __init__(self, name):
        print(name, "cannot swim.")
        super().__init__(name)


class Cat(donotSwim, donotFly):
    def __init__(self):
        print("A cat.")
        super().__init__("Cat")


cat = Cat()
print("")
bat = donotSwim("Bat")

출력:

A cat.
Cat cannot swim.
Cat cannot fly.
Cat is a mammal.
Cat is an animal.

Bat cannot swim.
Bat is a mammal.
Bat is an animal.

두 개의 상위 클래스donotswimdonotfly에 상속 된 하위 클래스Cat이 작성됩니다. 그런 다음 Mammals 클래스가 직접 상속합니다. Mammals클래스는 또한 수퍼 클래스Animals의 속성을 상속합니다. 따라서이 경우super()함수를 사용하여 수퍼 클래스 메소드에 쉽게 액세스했습니다.

관련 문장 - Python Class