클래스 상속 (Inheritance)
클래스 상속은 말 그대로 클래스를 물려받는 개념
기반이 되는 클래스를 부모 클래스(parent class) 또는 기반 클래스(base class), 슈퍼 클래스(super class) 라고 부르며, 물려받은 클래스를 자식 클래스(child class) 또는 파생 클래스(derived class), 서브 클래스(sub class) 라고 한다.
자식 클래스는 자기 자신의 메서드와 부모 클래스의 메서드를 모두 사용할 수 있습니다.
- 클래스를 매번 생성할 필요 없음
- 부모와 자식관계가 존재함
class 부모클래스:
# ...
class 자식클래스(부모클래스):
# ...
예시
# 부모 클래스
class Unit:
def __init__(self, name, hp):
self.name = name # 초기화
self.hp = hp
# 자식 클래스(부모 클래스)
class AttackUnit(Unit):
def __init__(self, name, hp, damage):
Unit.__init__(self, name, hp)
self.damage = damage
def attack(self, location):
print(
f'{self.name}: {location} 방향으로 상대 챔피언을 공격합니다. [공격력 {self.damage}]')
def damaged(self, damage):
print(f'{self.name} : {damage} 데미지를 입었습니다.')
self.hp -= damage
print(f'{self.name} : 현재 체력은 {self.hp} 입니다.')
if self.hp <= 0:
print(f'{self.name} : 처치당하였습니다.')
# 카이사 / 평타 (빠름 / 약함) / 빠르게 이동 가능
Kaisa_1 = AttackUnit("카이사", 450, 55)
Kaisa_1.attack("미드")
# 카이사: 미드 방향으로 상대 챔피언을 공격합니다. [공격력 55]
Kaisa_1.damaged(225)
Kaisa_1.damaged(225)
# 카이사 : 225 데미지를 입었습니다.
# 카이사 : 현재 체력은 225 입니다.
# 카이사 : 225 데미지를 입었습니다.
# 카이사 : 현재 체력은 0 입니다.
# 카이사 : 처치당하였습니다.
메소드 오버라이딩(Overriding)과 super()
메소드 오버라이딩은 상속 관계에서 동일한 메소드가 있을 때 특정 클래스의 메소드를 무시하고, 다른 클래스의 메소드를 사용하는 방식 이다. (오버라이딩은 기존에 이미 만들어진 메소드의 이름을 똑같이 만들어야할 때 사용)
class Phone:
def telecom(self):
print("통신사는 skt 입니다.")
class Sub_Phone(Phone):
def telecom(self):
print("통신사는 kt 입니다.")
test_1 = Sub_Phone()
test_1.telecom()
# 통신사는 kt 입니다.
만약 필요에 의해 오버라이딩한 자식 클래스의 telecome 메소드를 삽입 했으나 부모 클래스의 telecom 메소드도 같이 필요하다면 super() 를 이용하시면 된다.
class Phone:
def telecom(self):
print("통신사는 skt 입니다.")
class Sub_Phone(Phone):
def telecom(self):
super().telecom()
print("통신사는 kt 입니다.")
test_1 = Sub_Phone()
test_1.telecom()
# 통신사는 skt 입니다.
# 통신사는 kt 입니다.
super() : 부모 상속
하위 클래스에서 super()함수를 이용하여 상위 클래스의 init() 함수를 명시적으로 호출하여 name 값을 초기화 하는 것
class Person():
def __init__(self, name):
self.name = name
# Person 클래스를 상속
class EmailPerson(Person):
def __init__(self, name, email):
# 상위 클래스 Person의 __init__함수를 이용하여 name 값을 초기화
super().__init__(name)
self.email = email
if __name__ == "__main__":
p1 = EmailPerson("Kim", "Kim@kim.com")
print(p1.name + ' & ' + p1.email)
# 실행결과
# Kim & Kim@kim.com
class Parent:
def __init__(self, p1, p2):
'''super()를 사용하지 않으면 overriding 됩니다.'''
self.p1 = p1
self.p2 = p2
class Child(Parent):
def __init__(self, c1, **kwargs):
super(Child, self).__init__(**kwargs)
self.c1 = c1
self.c2 = "This is Child's c2"
self.c3 = "This is Child's c3"
child = Child(p1="This is Parent's p1",
p2="This is Parent's p1",
c1="This is Child's c1")
print(child.p1) # This is Parent's p1
print(child.p2) # This is Parent's p1
print(child.c1) # This is Child's c1
print(child.c2) # This is Child's c2
print(child.c3) # This is Child's c3
1) Child 클래스는 Parent 클래스를 상속
이는 Child 클래스내에 Parent 클래스의 메소드를 모두 가져오기 하는 것
2) 그러나 Parent 클래스와 Child 클래스는 모두 __init__()이라는 메소드를 가지고 있다.
따라서 super()를 사용하지 않으면, 부모 클래스의 __init__()는 자식 클래스의 __init__()에 의해 overriding(덮어쓰기) 된다.
3) Child 클래스의 __init__() 메소드에 Parent 클래스의 __init__() 메소드의 변수를 가지고 오고 싶으면,
Child 클래스의 __init__() 메소드내에서 super().__init__()을 입력하면 Parent 클래스의 __init__()에 있는 클래스 변수들을 가지고 올 수 있다.
4) super()는 상속받은 부모 클래스를 의미
5) 그러나 Parent 클래스의 _init__() 메소드에 argument가 있다면 Child 클래스는 _init__()에 **kwargs를 반드시 입력해야 한다.
또한 super().__init__()에도 반드시 **kwargs를 인자로 전달해 주어야 한다.
6) 5)을 하지 않으면 __init__() missing required positional arguments 에러가 발생한다.
<참고 : gwkoo.log >
소멸자
- 객체가 사라질 때 자동으로 호출되는 함수
class Account:
def __init__(self):
self.deposit = 0
print("계좌가 개설되었습니다!")
def save(self, money):
self.deposit += money
print("현재 계좌 잔액은 {}원 입니다.".format(deposit))
def __del__(self):
print("계좌가 폐쇄되었습니다. 이용해주셔서 감사합니다.")
acc = Account()
#계좌가 개설되었습니다!
del acc
# 계좌가 폐쇄되었습니다. 이용해주셔서 감사합니다.
'DL(Deep-Learning) > Python 기초' 카테고리의 다른 글
[Python] 파일과 디렉토리 경로 설정하기 (0) | 2022.01.26 |
---|---|
[Python] 예외처리 (0) | 2022.01.26 |
[Python] 클래스 Class 1 (0) | 2022.01.26 |
[python] 함수 Function (0) | 2022.01.26 |
[코드라이언] 번역하기 (0) | 2022.01.26 |