본문 바로가기
개발일지/Python

파이썬 class(클래스) 상속 기초원리6 재정의(오버라이딩)

by 개발에정착하고싶다 2022. 5. 20.
320x100
# 첫번째 케이스 로봇
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):

    # 1. 상속을 받았고
    # 2. 같은 이름이 함수를 정의해주는 것이고
    # 3. 상속받게된 함수의 기능을 사용하고 싶다면
    def __init__(self,c,h,w):
        super().__init__(c,h,w)
    # 이렇게 super().__init__()
    # 처리를 해주고

    # 위의 3가지 사항중 하나라도 해당사항이 없다면
    # 안쓰면 그만이다. super는
   def fire(self):
        print('레이저발사')
myRobot = NewRobot('white',300,330)
myRobot.printRobotInfo()
myRobot.fire()

 

 

# 두번째 케이스
# 삼각형 넓이를 구하는 것

class TriangleArea:

    def __init__(self, w, h):
        self.width = w
        self.height = h

    def printTriangleAreaInfo(self):
        print(f'self.width: {self.width}')
        print(f'self.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 f'triangleArea: {super().getArea()}cm'

ta = NewTriangleArea(7,5)
ta.printTriangleAreaInfo()
print(ta.getArea())
300x250