TIL - python(super)

한성봉·2021년 4월 21일

Super

  • super란 클래스 상속과 연관된 함수로 부모 클래스를 참조한다.
  • 자식 클래스에서 메소드 이름을 가지고 부모 클래스의 메소드를 사용할 수 있다.

super에 관련된 예시를 한번 살펴보자.

입력

class Animal(
    def __init__(self, name):
        self.name = name
    def walk(self):
        print("걷는다")
   def eat(self):
       print("먹는다")
    def greet(self):
        print("{}이/가 인사한다.". format(self.name))
class Human(Animal):
    def __init__(self, name, hand):
        super().__init__(name)
        self.hand = hand
    def wave(self):
        print("{}을 흔들면서". format(self.hand))
    def greet(self):
        self.wave()
        super().greet()
person = Human("사람", "오른손")
person.greet()

super는 부모클래스의 메서드를 자식클래스에서 사용할 수 있게 하는 명령어이다.
메서드 정의가 짧을 경우 활용성이 눈에 띄지 않을지는 모르겠으나 부모클래스의 메서드의 정의가 길어진다면 자식클래스에서 긴 코드들을 복사하는 것보다 super를 사용함으로 인해서 간결하게 메서드를 상속받을 수 있다.

0개의 댓글