[ Python ] 클래스 상속(Inheritance)

·2023년 4월 24일
0

[ Python ]

목록 보기
17/19

자식 클래스에 부모 클래스와 동일한 이름의 기능이 존재 시
자식 클래스의 인스턴스는 자신의 기능이 우선되므로,
부모 클래스의 기능도 함께 실행 시키기 위해서 super() 를 이용하여 호출

## 기능 구문
class Car:
  def __init__(self, colorV, speedV):
    self.color = colorV
    self.speed = speedV

class Sedan(Car):
  def __init__(self, colorV, speedV, doorV):
    self.door = doorV
    super().__init__(colorV, speedV)
    
  def carNum(self, number):
    self.number = number

## 호출 구문
if __name__ == "__main__":
  myCar = Sedan('pink',50,4)
  print(myCar.color, myCar.speed, myCar.door)
  
  myCar.carNum(5)
  print('mycar number: ', myCar.number)
  
>>> pink 50 4
>>> mycar number:  5

📌 클래스 다중상속

📒 예제

자동차 기능 중 속도 올리기 및 내리기의 기능이 구현된 클래스
✅  speedup(속도값): 속도값 만큼 속도 올리기
✅  speeddown(속도값): 속도값 만큼 속도 내리기

반자율주행 자동차 기능 중 자동운행인 ADAS 기능이 구현된 클래스
✅  ADAS(조정상태)
:: 조정상태에 입력되는 값은 - 'stop', 'accel'
✅  init 의 option은 'auto' 또는 'manual' 을 입력

Car 와 SemiSelfCar 의 다중상속 클래스
Car가 선행
✅  auto_map()으로 호출하고, "printing auto_map"을 출력
✅  auto_run()으로 호출하고, 속도값 출력


📌 클래스 다중상속 활용

🔻 믹스인 (mixin)
: 코드를 재사용하기 위해 일반적인 행동을 캡슐화해 놓은 부모클래스
( 서로 관련 없는 여러 서브클래스에서 코드를 재사용하기 위한 클래스 )

▪️ 대부분 다른 클래스의 메서드 또는 속성과 결합하여 사용
▪️ 믹스인클래스로 인스턴스 생성 불가
▪️ 믹스인클래스 상속 시 결합된 다른 클래스도 함께 상속
▪️ 장고(Django) 등에서 주로 사용

📒 예제

문장단어로 분리하고, 각 단어를 대문자로 변환하는 클래스 작성
✅  클래스 이름 : Tokenizer, UpperMixin, TokenUpper
✅  Tokenizer의 일부 기능을 부여 받아 추가 기능을 구현하는 클래스 생성

class Tokenizer:
  def __init__(self, sentence):
    self.sentence = sentence

  def __iter__(self):
    yield from self.sentence.split('/')

class UpperMixin:
  def __iter__(self):
    return map(str.upper, super().__iter__())

class TokenUpper(UpperMixin, Tokenizer):
  pass

if __name__ == "__main__":
  tk_upper1 = TokenUpper('year2003/month03/day24/object')
  print(list(tk_upper1))
  
>>> ['YEAR2003', 'MONTH03', 'DAY24', 'OBJECT']

문장문자로 분리하고, 각 글자를 대문자로 변환하는 클래스 작성
각 문자 사이에 * 을 삽입 하는 클래스 추가
✅  클래스 이름 : Deco, StrMixin, TokenJoin
✅  Tokenizer의 일부 기능을 부여 받아 추가 기능을 구현하는 클래스 생성

class Deco:
  def __init__(self, sentence):
    self.sentence = sentence
  
  def __iter__(self):
    yield from self.sentence

  def trans(self):
    return '*'.join(self.sentence)

class StrMixin:
  def __iter__(self):
    return map(str.upper, super().__iter__())

class TokenJoin(StrMixin, Deco):
  pass

if __name__ == "__main__":
  
  tk_join1 = TokenJoin('Python Happy')
  print(tk_join1.trans())

>>> P*y*t*h*o*n* *H*a*p*p*y

📌 메서드 오버라이딩(Overriding)

: 상위 클래스의 메서드를 서브 클래스에서 재정의

📒 예제

속도 올리기에서 승용차 클래스는 150 이상 불가한 경우
✅  부모 클래스 메서드에 추가 코드를 적용 시 super( ) 이용
✅  self.speed += plus ➡️ super( ). upSpeed( plus )

1️⃣ 오버라이딩이 적용되지 않은 코드

class Car:
  def __init__(self, color = 'black', speed):
    self.color = color
    self.speed = speed
    
  def upSpeed(self, plus):
    self.speed += plus

class Sedan(Car):
  def __init__(self, color, speed):
    super().__init__(color, speed)
  
myCar = Sedan('green', 80)
print(f'초기 속도: {myCar.speed}')
myCar.upSpeed(100)
print(f'업 속도: {myCar.speed}')

>>> 초기 속도: 80
>>> 업 속도: 180

2️⃣ 오버라이딩이 적용된 코드

class Car:
  def __init__(self, color = 'black', speed = 0):
    self.color = color
    self.speed = speed
    
  def upSpeed(self, plus):
    self.speed += plus

class Sedan(Car):
  def __init__(self, color, speed):
    super().__init__(color, speed)

  def upSpeed(self, plus):
    super().upSpeed(plus)
    if self.speed >= 150:
      self.speed = 150
  
myCar = Sedan('green', 80)
print(f'초기 속도: {myCar.speed}')
myCar.upSpeed(100)
print(f'업 속도: {myCar.speed}')

>>> 초기 속도: 80
>>> 업 속도: 150
profile
https://dribbble.com/ohseyun

0개의 댓글