오버라이딩(Overriding)?

Gangtaro·2022년 2월 2일
0
  • 오버라이딩(Overriding)이란 상속 관계에 있는 부모 클래스에서 이미 정의돈 메소드를 자식 클래스에서 같은 시그니처를 갖는 메소드로 다시 정의하는 것을 의미합니다.

  • 오버라이딩을 하는 것은, 부모 클래스에 있던 메소드를 자식 클래스만의 특별한 메소드로 만들기 위해서 하는 것이라고 생각합니다.

  • 메소드(method) 덮어쓰기라고 이해하고 있습니다.

Code로 이해하기

# 부모 클래스 = Animal
class Animal(object):
    def __init__(self, name) -> None:
        pass
        self.name = name
        print(f'{name} is registered on the system')
    
    def __repr__(self) -> str:
        return 'Grrr'
code_0001 = Animal('jason')
print(code_0001)
[실행결과]
jason is registered on the system
Grrr

위 코드는 Animal 이라는 Class를 만든 것이다. 다음으로 Animal의 자식 클래스로 Dog라는 클래스를 생성할 것입니다.

# 자식 클래스 = Dog
class Dog(Animal):
    def __init__(self, name) -> None:
        super().__init__(name)

    def __repr__(self) -> str:
        return 'Woof Woof'
ruby = Dog('Ruby')
print(ruby)
[실행결과]
Ruby is registered on the system
Woof Woof

이를 보면

  • __init__ method는 super().__init__(name) 이라는 명령을 함수 내부에 선언하는 것으로 method 자체를 상속 시켰다. (Overriding X)
  • __repr__ method는 __init__ method와는 다르게 부모클래스의 정보를 일절 상속받지 않고 새롭게 함수를 작성하였다. (Overriding)

Reference

0개의 댓글