본문 바로가기
Programming Languages/Python

[파이썬 코딩 테스트] super() 함수에서 클래스 상속과 코드 재사용

by Henry Cho 2026. 4. 2.

포스트 난이도: HOO_Junior


# super()

파이썬에서 다른 클래스의 mehtods를 사용할 수 있게 해주는 함수가 바로 super()이다. 이러한 다른 클래스에서 정의된 걸 가져와 사용하는 걸 상속(Inheritance)이라고 부르며, 부모 또는 자식 클래스라고 나눠서 부르기도 하지만 핵심은 다른 클래스에 있는 걸 가져와서 사용할 수 있게 한다는 것이다. 여기서 super()를 사용하는 이유는 코드 중복을 방지해 주며, 다중 상속에 있어서도 충돌을 방지해 주는 역할을 한다. 한마디로 여러 번 반복해서 methods를 정의할 필요가 없어지고 상속 클래스가 하나가 아니라 여러 개일 때 어떤 mehtods를 먼저 시작해야 할지가 super()를 통해서 명확해진다.

 

어떤 게 부모이고 자식 클래스인지 아는 방법은 클래스명 뒤에 괄호를 보면 바로 확인이 가능하다. 아래 예제를 살펴보면 class Bicycle이 부모 클래스이고 class ElectricBicycle(Bicylce)이 클래스명 뒤에 괄호로 부모 클래스명을 작성해 두었기에 자식 클래스인걸 확인할 수 있다.


class Bicycle:
    def start_journey(self):
        return "Journey started, happy cycling!"

class ElectricBicycle(Bicycle):
    def start_journey(self):
        # Llamamos al método de la clase padre usando super()
        base_message = super().start_journey()
        
        # Agregamos la funcionalidad o mensaje extra
        electric_message = " Motor engaged! Battery is at 100%."
        
        # Retornamos el mensaje combinado
        return base_message + electric_message

my_ride = ElectricBicycle()
print(my_ride.start_journey())  
# Output: Journey started, happy cycling! Motor engaged! Battery is at 100%.

Figure1. Result of example code 1


부모 클래스와 자식 클래스 확인이 되었다면 super()를 어떻게 써야할지 알 수 있다. class Bicycle에 정의한 start_journey를 ElectricBicycle 클래스에서 가져와 사용하고 싶다면 이때 super()를 통해서 다른 클래스의 methods를 빌려올 수 있다. 다만 한가지 유의할 점은 super()는 상속에 포함되어 있는 함수이기 때문에 자식 클래스에서 부모 클래스로 가져와 사용할 수는 없다. 이런 경우 self를 통해서 사용하면 되기에 꼭 자식 클래스 안에 있는 methods를 부모 클래스 안에 사용이 불가한 것은 아니다. 하지만 솔직히 굳이 이런 억지를 만들어야 하는 이유가 타당하지 않다면 안 쓰는 게 맞긴 하다. 이후에 결과를 출력해보면, 부모 클래스에서 정의된 문장과 자식 클래스에서 정의된 문장이 모두 출력되는 걸 확인할 수 있다.


# 추가 예제코드

class ElectronicDevice:
    def trun_on(self):
        print("Turning the device on ...")

class Computer(ElectronicDevice):
    def turn_on(self):
        super().trun_on()
        print("Loading the operating system ...")

my_computer = Computer()
my_computer.turn_on()

 

Figure2. Result of example code 2


위의 추가 예제코드의 경우에도 class Computer(ElectronicDevice) 안에서 super()를 사용해서 turn_on() methods를 부모 클래스에 해당하는 class ElectronicDevice에서 가져와 사용하는 걸 확인할 수 있다.


 

 

728x90

댓글