super 는 클래스에서 상속받을 때 초기화(?)하는 방법 중 하나이다.
부모 클래스를 다음과 같이 두자.
class Unit:
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
def move(self, location):
print("[지상 유닛 이동]")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))
상속받는 클래스 BuildingUnit 의 변수를 다음과 같이 초기화 할 수 있다.클래스 이름은 스타에서 건물.. 이라 speed 요소는 0. 근데 출력문구는 건물이고 뭐고 무시하고 내 맴대로 했다
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
Unit.__init__(self, name, hp, 0)
self.location = location
print("연진이는 {0}요, 체력이 {1}남았어요, 새벽{2}시 넘었어여".format(name, hp, location))
이제 여기서 다음과 같은 객체가 맞게 나온다.
whatthe = BuildingUnit("잠와..", 1, "2시")
>>> ㅇ진이는 잠와..요, 체력이 1남았어요, 새벽2시시 넘었어여
이걸 super 을 이용하여,
Unit.__init__(self, name, hp, 0) 대신하여
super().__init__(name, hp, 0) 로 나타낼 수 있다.
super도 마찬가지로 __init__을 통해 상속받아온다.
그러나 super 쓸 때는 첫 요소 자리에 self를 쓰지 않는다. 주의!
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
Unit.__init__(self, name, hp, 0)super().__init__(name, hp, 0)
self.location = location
print("ㅇ진이는 {0}요, 체력이 {1}남았어요, 새벽{2}시 넘었어여".format(name, hp, location)

다중상속 받을 때는?
결론부터 말하자면 super 못 쓴다. 그냥 클래스 하나하나 초기화(?)해야 함.
일단 부모클래스로 쓸 Unit, Flyable 을 다음과 같이 두자.
class Unit:
def __init__(self):
print("Unit 생성자")
class Flyable:
def __init__(self):
print("Flyable 생성자")
이제 상속받을 FlyableUnit을 super을 이용하여 다음과 같이 쓰고, dropship을 FlyableUnit으로 찍어내면,
class FlyableUnit(Unit, Flyable):
def __init__(self):
super().__init__()
dropship = FlyableUnit()
>>> Unit 생성자
Unit 생성자만 출력된다. 즉, Unit 클래스에 대해서만 상속받아온다.
아래와 같이 FlyableUnit이 상속받는 클래스 순서를 바꾸면
class FlyableUnit(Flyable, Unit):
def __init__(self):
super().__init__()
dropship = FlyableUnit()
>>> Flyable 생성자
Flyable 생성자 만 출력된다.. 이는 Flyable 클래스에 대해서만 상속받아온다는 뜻이고,
즉 super 는 다중상속 형식으로 쓰면 처음에 쓰인 부모 클래스에 대해서만 적용된다.
그러니 다중상속시에는 그냥 다음과 같이 처리하자.
class FlyableUnit(Flyable, Unit):
def __init__(self):
Unit.__init__(self)
Flyable.__init__(self)
dropship = FlyableUnit()
>>> Unit 생성자
Flyable 생성자
맞게 나온다.

'Python' 카테고리의 다른 글
클래스(멤버변수) (0) | 2022.09.27 |
---|---|
클래스(__init__) (0) | 2022.09.27 |