이번 포스팅에서는 Python의 클래스 오버라이딩과 클래스 변수에 대해서 알아 보록 하겠습니다.
클래스의 생성자와 상속에 대한 설명은 기존에 포스팅하였던 포스팅을 확인해주세요
2022.06.22 - [Coding, Testing, Challenge/Python-Middle] - Python 클래스 생성자와 상속
먼저 클래스 오버라이딩은 클래스를 상속했을 때 부모 클래스의 메서드를 재정의 하는 것을 말합니다.
아래의 코드는 부모 클래스인 Wapple을 상속한 자식 클래스 Crople에서 오버라이딩을 통해 메서드를 재정의 한 것입니다.
# 부모 클래스 선언
class wapple:
def __init__(self, menu, cream, toping):
self.menu = menu
self.cream = cream
self.toping = toping
print(f'{menu}은 크림은 {cream}, 토핑은 {toping}')
def check_toping(self):
print(f'{self.menu}은 토핑이 {self.toping}')
# 클래스 생성
plain = wapple("플레인와플", "생크림", "없습니다.")
choco = wapple("초코와플", "초코크림", "초코칩")
# 토핑 확인
plain.check_toping()
choco.check_toping()
# 자식 클래스 선언
class Crople(wapple):
def check_toping(self):
print(f'{self.menu}은 {self.toping}이 별도로 제공됩니다.')
# 자식클래스 생성
plain_crople = Crople("플레인크로플", "생크림", "없습니다.")
# 토핑 확인
plain_crople.check_toping()
결과를 보면 check_toping 메서드를 실행할 때 Crople 클래스와 Wapple 클래스의 동작이 다른 것을 알 수 있습니다.
생성자에 대한 오버라이딩도 가능합니다.
다음 코드는 Wapple을 상속한 Crople의 생성자를 오버라이딩한 코드입니다.
# 부모 클래스 선언
class wapple:
def __init__(self, menu, cream, toping):
self.menu = menu
self.cream = cream
self.toping = toping
print(f'{menu}은 크림은 {cream}, 토핑은 {toping}')
def check_toping(self):
print(f'{self.menu}은 토핑이 {self.toping}')
# 클래스 생성
plain = wapple("플레인와플", "생크림", "없습니다.")
choco = wapple("초코와플", "초코크림", "초코칩")
# 토핑 확인
plain.check_toping()
choco.check_toping()
# 자식 클래스 선언
class Crople(wapple):
def __init__(self, menu, cream, toping, baketime):
super().__init__(menu, cream, toping)
self.baketime = baketime
print(f'{menu}은 크림은 {cream}, 토핑은 {toping}, 굽기 시간은 {baketime}')
def check_toping(self):
print(f'{self.menu}은 {self.toping}이 별도로 제공됩니다.')
# 자식클래스 생성
plain_crople = Crople("플레인크로플", "생크림", "없습니다.", "20초")
# 토핑 확인
plain_crople.check_toping()
기존 Wapple과 다르게 생성 시 baketime 속성이 추가가 되었습니다.
생성자 오버라이딩에서 사용된 super()은 상속받는 부모 클래스를 지칭합니다.
위의 코드에서는 Wapple 클래스를 지칭하고 Wapple의 생성자를 실행 후 추가로 필요한 속성을 생성하였습니다.
실행 결과는 다음과 같습니다.
마지막으로 클래스 변수는 인스턴스들이 모두 함께 공유하는 변수입니다.
해당 클래스로 생성되는 인스턴스뿐만 아니라, 상속받은 인스턴스들에서도 공유가 됩니다.
다음 코드는 메뉴의 수인 menu_count를 만들고 인스턴스가 생성될 때마다 증가하는 코드입니다.
# 부모 클래스 선언
class wapple:
# 클래스변수
menu_count = 0
def __init__(self, menu, cream, toping):
self.menu = menu
self.cream = cream
self.toping = toping
print(f'{menu}은 크림은 {cream}, 토핑은 {toping}')
wapple.menu_count += 1
def check_toping(self):
print(f'{self.menu}은 토핑이 {self.toping}')
# 클래스 생성
plain = wapple("플레인와플", "생크림", "없습니다.")
print(plain.menu_count)
choco = wapple("초코와플", "초코크림", "초코칩")
print(choco.menu_count)
# 토핑 확인
plain.check_toping()
choco.check_toping()
# 자식 클래스 선언
class Crople(wapple):
def __init__(self, menu, cream, toping, baketime):
super().__init__(menu, cream, toping)
self.baketime = baketime
print(f'{menu}은 크림은 {cream}, 토핑은 {toping}, 굽기 시간은 {baketime}')
def check_toping(self):
print(f'{self.menu}은 {self.toping}이 별도로 제공됩니다.')
# 자식클래스 생성
plain_crople = Crople("플레인크로플", "생크림", "없습니다.", "20초")
print(plain_crople.menu_count)
# 토핑 확인
plain_crople.check_toping()
결과를 보면 wapple 뿐만 아니라 wapple을 상속한 Crople에서도 해당 변수가 증가하는 것을 확인할 수 있습니다.
이번 포스팅에서는 클래스의 오버라이딩과 클래스 변수를 알아보았습니다.
다음 포스팅에서는 파일 입출력에 대해서 알아보도록 하겠습니다.
'Coding, Testing, Challenge > Python-Middle' 카테고리의 다른 글
Python 파일 입출력 (0) | 2022.08.03 |
---|---|
Python 클래스 생성자와 상속 (0) | 2022.06.22 |
Python 클래스와 객체 (0) | 2022.06.21 |