클래스 상속 시, 부모 클래스의 속성과 메서드를 자식 클래스에서 어떻게 호출할 수 있나요?
  1. super() 함수를 사용하여 호출:
    • 자식 클래스의 생성자 내에서 super() 함수를 호출하여 부모 클래스의 생성자를 실행할 수 있습니다. 이렇게 하면 부모 클래스의 속성과 메서드에 접근할 수 있습니다.
    • 부모 클래스의 생성자를 호출한 이후에는 자식 클래스의 속성과 메서드를 정의하거나 재정의할 수 있습니다.
    class Parent:
        def __init__(self):
            self.attribute = "Parent attribute"
    
        def parent_method(self):
            print("This is a parent method")
    
    class Child(Parent):
        def __init__(self):
            super().__init__()  # 부모 클래스의 생성자 호출
            self.child_attribute = "Child attribute"
    
        def child_method(self):
            print("This is a child method")
    
    child = Child()
    print(child.attribute)  # "Parent attribute" 출력
    child.parent_method()   # "This is a parent method" 출력
    
  2. 부모 클래스의 속성과 메서드에 접근:
    • 자식 클래스의 메서드 내에서 self 키워드를 사용하여 부모 클래스의 속성과 메서드에 직접 접근할 수 있습니다.
    class Parent:
        def __init__(self):
            self.attribute = "Parent attribute"
    
        def parent_method(self):
            print("This is a parent method")
    
    class Child(Parent):
        def child_method(self):
            print(self.attribute)  # 자식 클래스에서 부모 클래스의 속성에 접근
            self.parent_method()   # 자식 클래스에서 부모 클래스의 메서드 호출
    
    child = Child()
    child.child_method()  # "Parent attribute"와 "This is a parent method" 출력
    

클래스 상속을 통해 부모 클래스의 속성과 메서드를 자식 클래스에서 사용할 수 있으므로 코드의 재사용성과 유지보수성을 향상시킬 수 있습니다. 자식 클래스는 부모 클래스의 기능을 확장하거나 변경하여 새로운 기능을 추가할 수 있습니다. 보다 자세한 내용은 파이썬 공식 문서나 기타 참고 자료를 참조하시기 바랍니다.

#Python #클래스상속