오버라이딩
하위 클래스에서 상위 클래스의 메서드를 재정의(override)한다.
상위 클래스의 메서드 이름과 동일한 메서드를 상속받은 하위 클래스에서 다시 자체적으로 구현하는 것
Robot
fire() ─▶ '총알 발사~!'
▲ ▲ │ 상속 │ │ │메서드 오버라이딩 │ │ │ │ NewRobot │
|
class Robot: def __init__(self, c, h, w): self.color = c self.height = h self.weight = w
def fire(self): print('총알 발사~!')
class NewRobot(Robot): def __init__(self, c, h, w): super().__init__(c, h, w)
def fire(self): super().fire() print('레이저 발사~!') |
class Robot:
def __init__(self, c, h, w):
self.color = c
self.height = h
self.weight = w
def fire(self):
print('총알 발사~!')
def printRobotInfo(self):
print(f'self.color: {self.color}')
print(f'self.height: {self.height}')
print(f'self.weight: {self.weight}')
class NewRobot(Robot):
def __init__(self, c, h, w):
super().__init__(c, h, w)
myRobot = NewRobot('red', 200, 50)
myRobot.printRobotInfo()
myRobot.fire()
-- 출력 -- |
self.color: red self.height: 200 self.weight: 50 총알 발사~! |
class Robot:
def __init__(self, c, h, w):
self.color = c
self.height = h
self.weight = w
def fire(self):
print('총알 발사~!')
def printRobotInfo(self):
print(f'self.color: {self.color}')
print(f'self.height: {self.height}')
print(f'self.weight: {self.weight}')
class NewRobot(Robot): #Robot 클래스 상속
def __init__(self, c, h, w):
super().__init__(c, h, w)
def fire(self): #fire 메서드 오버라이딩
print('레이저 발사~!')
myRobot = NewRobot('red', 200, 50)
myRobot.printRobotInfo()
myRobot.fire()
-- 출력 -- |
self.color: red self.height: 200 self.weight: 50 레이저 발사~! |
[실습] 삼각형 넓이를 계산하는 TriangleArea 클래스를 상속하는 클래스에서 getArea()를 오버라이딩 해서
출력 결과가 다음과 같을 수 있도록 클래스를 만들어 보자.
class TriangleArea: def __init__(self, w, h): self.width = w self.height = h
def printTriangleAresInfo(self): print(f'width: {self.width}') print(f'height: {self.height}')
def getArea(self): return self.width * self.height / 2 |
--출력 결과-- witdh: 7 height: 5 Triangle Area: 17.5㎠ |
class TriangleArea:
def __init__(self, w, h):
self.width = w
self.height = h
def printTriangleAresInfo(self):
print(f'width: {self.width}')
print(f'height: {self.height}')
def getArea(self):
return self.width * self.height / 2
class NewTriangleArea(TriangleArea):
def __init__(self, w, h):
super().__init__(w, h)
def getArea(self):
return str(super().getArea()) + '㎠'
myTriangle = NewTriangleArea(7, 5)
myTriangle.printTriangleAresInfo()
taArea = myTriangle.getArea()
print(f'Triangle Area: {taArea}')
-- 출력 -- |
witdh: 7 height: 5 Triangle Area: 17.5㎠ |