클래스 상속을 통해 부모 클래스의 생성자 함수를 오버라이딩하는 방법은 무엇인가요?
class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
child = Child("John", 10)
print(child.name) # 출력: John
print(child.age) # 출력: 10
위의 예시 코드에서는 Child
클래스가 Parent
클래스를 상속받고 있습니다. Child
클래스에서 __init__
메서드를 정의하면서 super().__init__(name)
을 호출하여 부모 클래스의 생성자 함수를 오버라이딩하고, age
변수를 추가로 초기화하고 있습니다.
이렇게 하면 Child
클래스의 인스턴스를 생성할 때 Parent
클래스의 생성자 함수도 호출되어 name
변수가 초기화되며, Child
클래스에서 추가로 정의한 age
변수도 초기화됩니다.