Python Inheritance

김신영·2024년 9월 23일

Python

목록 보기
3/10
post-thumbnail

상속(Inheritance)

  • 자식 클래스가 부모 클래스의 모든 속성과 메서드를 물려받는 것.

    class Parent:
        def parent_method(self):
            print("This is a parent method")
    
    class Child(Parent):  # Parent 클래스를 상속받음
        pass
    
    c = Child()
    c.parent_method()  # 부모의 메서드를 호출할 수 있음

메서드 오버라이딩(Method Overriding)

  • 자식 클래스가 부모 클래스의 메서드를 동일한 이름으로 재정의하는 것.

  • 자식 클래스에서 부모의 동작을 수정할 수 있음.

    class Parent:
        def greet(self):
            print("Hello from Parent")
    
    class Child(Parent):
        def greet(self):  # 메서드 오버라이딩
            print("Hello from Child")
    
    c = Child()
    c.greet()  # "Hello from Child" 출력

부모 메서드 호출하기 (super())

  • 오버라이딩된 메서드에서 부모 클래스의 메서드를 호출할 수 있음.

  • super()는 부모 클래스의 메서드나 속성을 명시적으로 호출할 때 사용.

    class Parent:
        def greet(self):
            print("Hello from Parent")
    
    class Child(Parent):
        def greet(self):
            super().greet()  # 부모의 메서드를 호출
            print("Hello from Child")
    
    c = Child()
    c.greet()  
    
    # "Hello from Parent"
    # "Hello from Child"

다중 상속(Multiple Inheritance)

  • 한 클래스가 두 개 이상의 부모 클래스를 상속받을 수 있음.

  • 다중 상속 시 상속 순서에 따라 메서드가 호출되며, 충돌이 발생할 수 있으므로 주의해야 함.

    class A:
        def method(self):
            print("Method from A")
    
    class B:
        def method(self):
            print("Method from B")
    
    class C(A, B):  # A와 B를 다중 상속
        pass
    
    c = C()
    c.method()  # "Method from A" 출력 (상속 순서에 따라)

MRO (Method Resolution Order)

  • MRO는 다중 상속 시 메서드를 호출하는 순서를 결정함.

  • mro() 메서드는 클래스의 상속 순서를 확인하는 데 사용됨.

    class A:
        pass
    
    class B(A):
        pass
    
    class C(B):
        pass
    
    print(C.mro())  # 클래스의 상속 순서 출력
    
    # [<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]

MRO는 특히 다중 상속에서 메서드 충돌이 발생할 경우 Python이 어떤 순서로 메서드를 찾을지 결정하는 중요한 개념입니다.

profile
Hello velog!

0개의 댓글