- 개요
https://monstrosite.tistory.com/17
객체지향 프로그래밍의 3요소 - 상속성
객체지향 프로그래밍(Object Oriented Programming) 줄여서 OOP의 3가지 요소에 대해 알아보고자 합니다.첫 번째 시작으로, 상속성에 대해 알아보겠습니다. 위의 코드에서 Knight 클래스는 아주 간단하게
monstrosite.tistory.com
파이썬에서 클래스의 메서드 간의 오버라이딩을 통해 상속성을 구현하는 방법을 알아본다
1) 상속된 프로퍼티가 전달되는 시점
class ParentEx1():
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class ChildEx1(ParentEx1):
pass
위와 같은 클래스 구조를 생성하였다
부모 클래스 ParentEx1으로부터 자식 클래스 ChildEx1이 상속되었다
자식 클래스는 아무런 정의없이 단순히 부모 클래스의 구조를 상속받았다
c1 = ChildEx1()
p1 = ParentEx1()
print(f"ChildEx1 Class : {ChildEx1.__dict__}")
print(f"ParentEx1 Class : {ParentEx1.__dict__}")
print(f"ChildEx1 Instance : {c1.__dict__}")
print(f"ParentEx1 Instance : {p1.__dict__}")
이후 위와 같이 부모 클래스의 객체와 자식 클래스의 객체를 각각 생성하였다
이어서 __dict__ 메서드를 사용하여 클래스의 객체가 가진 정보에 접근하여 값을 출력한다

출력 결과를 확인해보면 클래스 상태에서는 프로퍼티를 확인할 수 없지만,
인스턴스 상태에서는 프로퍼티 value를 확인할 수 있다
따라서 프로퍼티는 클래스의 인스턴스가 생성되면 전달된다
2) 메서드 오버라이딩
class ParentEx2():
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class ChildEx2(ParentEx2):
def get_value(self):
return self.value * 10
c2 = ChildEx2()
print(f"c2 value : {c2.get_value()}")
파이썬에서 부모 클래스의 함수를 재정의하는 오버라이딩은 매우 간단하다
상속받은 함수에 로직을 덮어씌우면 오버라이딩을 적용한다

위 코드의 실행 결과는 위와 같다
3) 부모 버전의 함수 호출
class ParentEx3():
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class ChildEx3(ParentEx3):
def get_value(self):
print("using parent`s value")
return super().get_value() * 100
def get_value2(self):
print("using parent`s value 2")
return super(ChildEx3, self).get_value()
c3 = ChildEx3()
print(f"c3 value : {c3.get_value()}")
print(f"c3 value : {c3.get_value2()}")
부모 버전의 함수를 호출은 2)와는 다르게 조금 복잡하다
2가지 방법이 있는데, 공통적으로 super 키워드를 사용한다
- 첫번째 방법 : super().호출할함수명()
- 두번째 방법 : super(자식클래스명, self).호출할함수명()
위의 2가지 방법으로 부모의 함수를 호출할 수 있다

실행 결과는 위와 같다
'Python > 파이썬 오픈소스 배포' 카테고리의 다른 글
| 메타 클래스 (1) (0) | 2025.07.04 |
|---|---|
| 메서드 오버로딩 (0) | 2025.07.02 |
| Getter 메서드와 Setter 메서드 (0) | 2025.07.01 |
| 언더스코어(_)의 사용 (0) | 2025.06.30 |
| Context Manager Annotation (0) | 2025.06.27 |