클래스 상속을 통해 부모 클래스의 메서드를 액세스하는 방법은 무엇인가요?

자식 클래스에서 부모 클래스의 메서드를 액세스하는 방법은 간단합니다. 자식 클래스의 메서드 안에서 super 키워드를 사용하여 부모 클래스의 메서드를 호출할 수 있습니다. 다음은 이에 대한 예시 코드입니다.

class Parent:
    def __init__(self):
        self.name = "Parent"
    
    def say_hello(self):
        print("Hello from", self.name)

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.name = "Child"
    
    def say_hello(self):
        super().say_hello()
        print("Hello again from", self.name)

child = Child()
child.say_hello()

이 예시 코드는 Parent 클래스와 Child 클래스를 정의하고, Child 클래스가 Parent 클래스를 상속받는 예시입니다. Child 클래스의 __init__ 메서드에서 super().__init__()를 호출하여 Parent 클래스의 초기화 메서드를 사용하고, super().say_hello()를 호출하여 Parent 클래스의 say_hello 메서드를 호출합니다.

실행 결과는 다음과 같습니다.

Hello from Parent
Hello again from Child

이를 통해 자식 클래스에서는 부모 클래스의 메서드를 호출하고, 필요에 따라 재정의하여 사용할 수 있음을 확인할 수 있습니다.

더 자세한 내용은 아래의 참고 자료를 확인하시기 바랍니다.

#Python #상속