상속과 다형성

상속 Inheritance

class 자식클래스(부모클래스):
    메서드들...
class Animal():
    def walk(self):
        print("걷는다.")
    def eat(self):
        print("먹는다.")
    
class Human(Animal):
    def wave(self):
        print("손을 흔든다.")
        

class Dog(Animal):
    def wag(self):
        print("꼬리를 흔든다.")
  • 상속하는 클래스를 부모 클래스

  • 상속받는 클래스를 자식 클래스

  • 자식 클래스가 부모 클래스의 내용을 가져다 쓸 수 있는 것

다중 상속

class 자식클래스(부모클래스1, 부모클래스2, 부모클래스3):
    메서드들...
  • 상속된 어트리뷰트를 검색은 깊이 우선으로, 왼쪽에서 오른쪽 순서로 찾는다.

    • 자식클래스 > 부모클래스1 > 부모클래스2 > 부모클래스3

다형성

  • super: 부모의 동작을 그대로 진행하면서, 추가하고 싶을 경우.

    • __init__에서 많이 사용된다.

class Animal( ):
    def __init__( self, name ):
        self.name = name
        
    def greet( self ):
        print( "인사한다" )

class Human( Animal ):
    def __init__( self, name, hand ):
        super().__init__( name ) # 부모클래스의 __init__ 메소드 호출
        self.hand = hand
        
    def greet( self ):
        print( "손을 흔든다" )
        super().greet()

class Dog( Animal ):
    def greet( self ):
        print( "꼬리를 흔든다" )
        
person = Human("사람", "오른손")

Last updated