super() 함수
Coddy Python 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 64개 중 18번째.
super() 함수는 자식 클래스가 부모 클래스의 메서드를 호출할 수 있게 해줍니다. 이를 통해 부모의 기능을 완전히 대체하는 대신 확장할 수 있습니다.
다음은 생성자에서 super()를 사용하는 예시입니다:
class Animal:
def __init__(self, name):
self.name = name
print(f"Animal created: {name}")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # 부모의 __init__ 호출
self.breed = breed
print(f"Dog breed set: {breed}")dog 객체를 생성합니다:
buddy = Dog("Buddy", "Golden Retriever")
print(f"Name: {buddy.name}, Breed: {buddy.breed}")출력:
Animal created: Buddy
Dog breed set: Golden Retriever
Name: Buddy, Breed: Golden Retriever부모 메서드를 확장하려면 super()를 사용하세요:
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self):
super().make_sound() # 먼저 부모의 메서드를 호출합니다
print("Woof!") # 개 특유의 동작을 추가합니다확장된 메서드를 호출합니다:
buddy = Dog()
buddy.make_sound()출력:
Generic animal sound
Woof!super()가 없으면 부모의 기능을 잃게 됩니다:
class Cat(Animal):
def make_sound(self):
print("Meow!") # 고양이 소리만 나고, 부모 메서드는 무시됩니다
cat = Cat()
cat.make_sound()출력:
Meow!핵심 포인트: 자식 클래스에서 부모 클래스의 메서드를 호출하려면 super()를 사용하세요. 이를 통해 기능을 완전히 대체하는 대신 확장할 수 있습니다. 일반적인 용도로는 부모의 __init__ 메서드 호출 및 부모 동작 확장이 있습니다.
챌린지
중급이 챌린지에서는 상속을 사용하여 Person 및 Employee 클래스 계층 구조를 구현합니다.
person.py: name 및 age 속성을 가진 Person 클래스를 포함합니다employee.py: Person을 상속받는 Employee 클래스를 포함합니다driver.py: 구현을 테스트하기 위한 메인 파일입니다
각 파일에는 구현을 안내하는 자세한 TODO 주석이 포함되어 있습니다.
치트 시트
super() 함수는 자식 클래스가 부모 클래스의 메서드를 호출할 수 있게 하여, 기능을 대체하는 대신 확장할 수 있도록 합니다.
생성자에서 super() 사용하기:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # 부모의 __init__ 호출
self.breed = breed메서드 확장을 위해 super() 사용하기:
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self):
super().make_sound() # 부모의 메서드를 먼저 호출
print("Woof!") # 자식 클래스 전용 동작 추가super()가 없는 경우: 자식 메서드가 기능을 확장하는 대신 부모의 기능을 완전히 대체합니다.
직접 해보기
# TODO: person.py에서 Person 클래스를 가져오세요
# TODO: employee.py에서 Employee 클래스를 가져오세요
def main():
# TODO: 이름이 "Alice"이고 나이가 30인 Person 객체를 생성하세요
person = None
# TODO: 이름이 "Bob", 나이가 35, 직업이 "Developer"인 Employee 객체를 생성하세요
employee = None
# TODO: Person 객체에서 introduce() 메서드를 호출하세요
# 예상 출력: "Hi, I'm Alice and I'm 30 years old"
# TODO: 간격을 위해 빈 줄을 출력하세요 - print()
# TODO: Employee 객체에서 introduce() 메서드를 호출하세요
# 예상 출력:
# "Hi, I'm Bob and I'm 35 years old"
# "I work as a Developer"
if __name__ == "__main__":
main()이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.