[Python] 클래스 상속 - super(), 메서드 재정의, name mangling(_클래스명__변수명)
by 우와한개발자
1. 기본 문법
- 자식 클래스가 부모 클래스의 변수와 메서드를 물려받음
- 다중 상속 가능
class 자식클래스명(부모클래스명):
...
class 자식클래스명(부모클래스명1, 부모클래스명2, ...):
...
2. super()
- 자식 클래스에서 부모 클래스의 멤버(변수, 메서드)를 참조할 때 사용
- super().메서드명() 형식으로 호출
- self가 자동으로 전달되므로 직접 넘기지 않아도 됨
- super().__init__() 으로 부모 생성자 호출해 초기화 가능
class Person:
def __init__(self, name, gender):
self.name = name
self.gender = gender
def print_info(self):
print(f'{self.name}님은 {self.gender}입니다.')
class Student(Person):
def __init__(self, name, gender, major):
super().__init__(name, gender) # 부모 생성자 호출 — self 자동 전달
self.major = major
def print_info(self):
super().print_info() # 부모 메서드 호출
print(f'전공 : {self.major}')
s1 = Student('홍길동', '남자', '경제학')
s1.print_info()
# 홍길동님은 남자입니다.
# 전공 : 경제학
3. 재정의
- 부모클래스에서 정의한 함수를 자식클래스에서 다시 정의 가능
- 메서드 이름과 파라미터가 같아야 함
- 호출 시 부모 메서드 대신 자식 메서드가 실행됨
class Student(Person):
def __init__(self, name, gender, major):
super().__init__(name, gender)
self.major = major
def print_info(self): # Person의 print_info 재정의
print(f'{self.name}님은 {self.gender}이며, 전공은 {self.major}입니다.')
s1 = Student('홍길서', '여자', '경제학')
s1.print_info()
# 홍길서님은 여자이며, 전공은 경제학입니다. ← 자식 메서드 실행
p1 = Person('홍길동', '남자')
p1.print_info()
# 홍길동님은 남자입니다. ← 부모 메서드 실행
4. 정적변수 (__ 변수명 : name mangling)
- 객체들 사이에서 데이터를 공유하고 싶을 때 사용
- 변수명 앞에 __(언더스코어 2개)를 붙이면 외부에서 직접 접근 불가
- Name Mangling = 파이썬이 __변수명을 내부적으로 _클래스명__변수명으로 이름을 바꿔서 저장하는 것
- 참조 시 클래스명._클래스명__변수명 형식 사용 (name mangling 자동 적용)
class Student(Person):
__count = 0 # 정적변수 — 외부 직접 접근 불가
def __init__(self, name, gender, major):
super().__init__(name, gender)
self.major = major
Student._Student__count += 1 # 정적변수 참조
def __del__(self):
Student._Student__count -= 1
@classmethod
def get_count(cls):
return cls._Student__count # 클래스 메서드로 접근하는 게 더 깔끔
s1 = Student('홍길동', '남자', '경제학')
s2 = Student('김철수', '남자', '컴퓨터공학')
print(Student.get_count()) # 2
del s1
print(Student.get_count()) # 1
class MyClass:
def __init__(self):
self.__private = "진짜 숨김"
obj = MyClass()
print(obj.__private) # ❌ 오류 (접근 불가)
print(obj._MyClass__private) # ✅ "진짜 숨김" (실제 저장된 이름)'언어 > Python' 카테고리의 다른 글
| [Python] 파일 읽고 쓰기 - %%writefile, open(), read/write, 피클(pickle) (0) | 2026.04.19 |
|---|---|
| [Python] 예외처리 - try/except, raise, 추상클래스, 사용자 정의 예외 (0) | 2026.04.19 |
| [Python] 클래스 메서드, 정적 메서드, 생성자와 소멸자 - @classmethod, @staticmethod, __init__ (0) | 2026.04.19 |
| [Python] 클래스(class)와 객체(object) - 구조, 네임스페이스, self (0) | 2026.04.19 |
| [Python] 패키지(package)와 pyc 파일 - __init__.py, __pycache__ 폴더 (0) | 2026.04.19 |
블로그의 정보
우와한개발자 님의 블로그
우와한개발자