-
[python] superpython 2025. 5. 28. 17:09
super
Python에서 super()는 부모 클래스(상위 클래스)의 메서드를 호출할 때 사용하는 함수입니다.
✅ super()란?
자식 클래스에서 부모 클래스의 메서드를 호출하는 함수
super()는 상속 관계에서 자식 클래스가 부모 클래스의 메서드(예: __init__(), 일반 메서드)를 명시적으로 호출할 때 사용됩니다.
📌 사용 예시
class Parent: def __init__(self): print("부모 생성자 호출") class Child(Parent): def __init__(self): super().__init__() # 부모 생성자 호출 print("자식 생성자 호출") child = Child()
부모 생성자 호출
자식 생성자 호출✅ 왜 super()를 사용하나요?
- 코드를 중복 없이 재사용할 수 있음
- 다중 상속(Multiple Inheritance) 상황에서도 안전하게 부모 메서드를 호출할 수 있음
- 부모 클래스가 바뀌어도 유연하게 유지보수 가능
👨💻 super() vs 직접 클래스명 호출
# 두 방식 모두 가능 super().__init__() # 권장 방식 Parent.__init__(self) # 가능하지만 하드코딩된 부모 이름
super()는 클래스 이름을 고정하지 않아 다중 상속 시 더 안전하고 유연합니다.
💡 실용 예제: 상속에서 super()로 초기화
class Unit: def __init__(self, name, hp): self.name = name self.hp = hp class AttackUnit(Unit): def __init__(self, name, hp, damage): super().__init__(name, hp) # 부모 클래스 Unit 초기화 self.damage = damage
✅ 요약
역할 부모 클래스의 메서드 호출 장점 중복 제거, 다중 상속 대응, 유지보수 용이 사용 예시 super().__init__() 비교 Parent.__init__(self)보다 super()가 더 일반적이고 유연함 실습
class Unit: def __init__(self): print("Unit 생성자") class Flyable: def __init__(self): print("Flyable 생성자") class FlyableUnit(Flyable, Unit): def __init__(self): Unit.__init__(self) Flyable.__init__(self) # 드랍쉽 dropship = FlyableUnit()
Unit 생성자
Flyable 생성자'python' 카테고리의 다른 글
[python] 예외처리 (1) 2025.05.29 [python] 스타크래프트 프로젝트 (0) 2025.05.29 [python] pass (0) 2025.05.28 *[python] 메소드 오버라이딩 (0) 2025.05.28 [python] 다중상속 (0) 2025.05.28