git 바로가기
상속
다중 상속
super
상속
- java와 같이 클래스에서 하나의 클래스를 받아 상위 클래스(부모 클래스)의 함수나 변수를 사용할 수 있게 하는 것
- 자식클래스에서는 부모클래스의 속성과 메소드는 기재하지 않아도 포함이 됩니다.
class 부모클래스:
...내용...
class 자식클래스(부모클래스):
...내용...
class Unit:
def __init__(self, name, hp, speed):
# __init__ 생성자
self.name = name# 멤버변수, 클래스안에서만 사용하는
self.hp = hp
self.speed = speed
print("체력 {0}, 스피드{1}인 {2} 유닛이 생성되었습니다,".format(hp, speed, name))
def move(self, location):
print("[지상 유닛 이동]")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
self.hp -= damage
print("{0} : 현재 체력은 {1} 입니다. ".format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
class AttackUnit(Unit):#Unit클래스 상속
def __init__(self, name, hp, speed, damage):
Unit.__init__(self, name, hp, speed)
self.name = name
self.hp = hp
self.speed = speed
self.damage = damage
print("공격력 {0}".format(damage))
def attack(self, location):
print("{0} : {1} 방향으로 적국을 공격합니다. [공격력 {2}]"\
.format(self.name, location, self.damage))
# AttackUnit 생성(Unit클래스를 상속하고있기때문에 그에 맞는 인스턴스와 함께)
firebat1 = AttackUnit("파이어뱃", 50, 2, 16)
# AttackUnit의 attack 함수 사용
firebat1.attack("5시")
# 상속하고있는 Unit의 damaged 함수 사용
firebat1.damaged(25)
다중 상속
- 상속할 클래스가 다 수 인것
- Java는 안되지만 c++이나 Python은 가능하다
class 부모클래스1:
...내용...
class 부모클래스2:
...내용...
class 자식클래스(부모클래스1, 부모클래스2):
...내용...
# ... 상위 Unit과 AttackUnit클래스 첨부
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
.format(name, location, self.flying_speed))
class FlyableAttackUnit(AttackUnit, Flyable):# 다중상속
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) #지상 speed 0
Flyable.__init__(self, flying_speed)
def move(self, location):# 연산자 오버로딩
print("[공중 유닛 이동]")
self.fly(self.name, location)
super
- 오버라이딩으로 부모와 같은 메소드가 정의 되어있는 상태에서 부모의 메소드와 자식의 메소드 둘다 사용해야하는 경우에 사용한다.
class Country():
def show(self):
print("부모 클래스의 show 메소드다")
class Korea(Country):
... 생략
def show(self):
super().show()
print(
"""
국가의 이름은 {} 입니다.
국가의 인구는 {} 입니다.
국가의 수도는 {} 입니다.
""".format(self.name, self.population, self.capital)
)