클래스 심화 강의 수강 중 정리가 필요한 것이 생겨서 작성
- 부모 / 자식 클래스 (클래스 상속, super)
class ParentClass():
def __init__(self, name):
self.name = name
pass
def greeting(self)
print(f"{self.name}님 안녕하세요.")
# 클래스 상속 방법: class 자식클래스명(부모클래스명)
# 클래스 선언 후 아래 코드 작성 시 super()를 통해 부모 클래스의 메서드를 그대로 사용할 수 있다.
# super()를 사용하지 않아도 이미 상속받은 상태라 부모 클래스의 메서드를 사용할 수 있지만
# 자식 클래스에서 부모 메서드와 같은 이름의 메서드를 정의했을 때 super()를 사용하지 않으면
# overriding 하게 되어 부모 클래스의 메서드에 영향을 준다.
# 즉 super()를 사용해야 overriding을 피할 수 있다.
class ChildClass(ParentClass):
def __init__(self, name):
super().__init__(name)
# test_01에 자식 클래스 상속
test_01 = ChildClass("child_class")
# test_01에서 부모 클래스의 greeting 메서드 사용 가능
test_01.greeting()
# 실행하면 child_class님 안녕하세요. 출력
강의 중 예제 코드
class Monster():
def __init__(self, hp):
self.hp = hp
def attack(self, damage):
self.hp -= damage
def status_check(self):
print(f"monster's hp : {self.hp}")
class FireMonster(Monster):
def __init__(self, hp):
self.attribute = "fire"
# super()를 사용하면 부모 클래스의 코드를 그대로 사용할 수 있습니다.
# 해당 코드는 self.hp = hp 코드를 실행시키는 것과 동일합니다.
super().__init__(hp)
# 부모 클래스에 존재하는 status_check 메소드를 overriding 합니다.
def status_check(self):
print(f"fire monster's hp : {self.hp}")
class IceMonster(Monster):
def __init__(self, hp):
self.attribute = "ice"
super().__init__(hp)
def status_check(self):
print(f"ice monster's hp : {self.hp}")
fire_monster = FireMonster(hp=100)
# FireMonster 클래스에는 attack 메소드가 없지만
# 부모 클래스에서 상속받았기 때문에 별도의 선언 없이 사용 가능합니다.
fire_monster.attack(20)
fire_monster.status_check()
ice_monster = IceMonster(hp=200)
ice_monster.attack(50)
ice_monster.status_check()
강의 내용 중에
"그리고 여기서 조금 더 좋은 코드를 짜고 싶다, 그러면 (부모 클래스) status_check에서 self.attribute를 출력하게 하면 (자식 클래스에서) status_check를 새로 선언할 필요가 없다."
라는 내용이 있다.
아래는 이를 적용한 코드
class Monster():
def __init__(self, hp, attr=None):
self.hp = hp
self.attribute = attr
def attack(self, damage):
self.hp -= damage
def status_check(self):
attr_str = self.attribute + ' ' if self.attribute else ''
print(f"{attr_str}monster's hp : {self.hp}")
class FireMonster(Monster):
def __init__(self, hp):
super().__init__(hp, attr="fire")
class IceMonster(Monster):
def __init__(self, hp):
super().__init__(hp, attr="ice")
fire_monster = FireMonster(hp=100)
fire_monster.attack(20)
fire_monster.status_check()
ice_monster = IceMonster(hp=200)
ice_monster.attack(50)
ice_monster.status_check()
두 코드의 실행 결과는 같다.
'PYTHON' 카테고리의 다른 글
[TIL] 20240227 11일차 (1) | 2024.02.27 |
---|---|
[TIL] 20240226 10일차 (1) | 2024.02.26 |
[TIL] 20240223 9일차 (0) | 2024.02.23 |
[TIL] 20240222 8일차 (0) | 2024.02.22 |
[TIL] 20240219 5일차 (0) | 2024.02.19 |