Menu
Coddy logo textTech

메서드 오버라이딩

Coddy Python 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 64개 중 19번째.

메서드 오버라이딩을 통해 자식 클래스는 부모 클래스에 이미 존재하는 메서드에 대해 자체적인 구현을 제공할 수 있습니다.

다음은 메서드가 포함된 부모 클래스의 예입니다:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

하나의 메서드를 오버라이드하는 자식 클래스를 생성합니다:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")  # 부모 메서드를 오버라이드합니다

Dog의 make_sound 메서드는 Animal의 메서드를 대체하지만, info는 여전히 변경되지 않은 채로 상속됩니다.

인스턴스를 생성하고 메서드를 테스트해 보세요:

animal = Animal("Generic Animal")
dog = Dog("Buddy")

오버라이드된 메서드를 호출합니다:

animal.make_sound()
dog.make_sound()

오버라이드되지 않은 메서드를 호출합니다:

animal.info()
dog.info()

출력:

Some generic animal sound
Woof! Woof!
I am Generic Animal
I am Buddy

상속받은 모든 메서드를 오버라이드할 수 있습니다:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

cat = Cat("Whiskers")
cat.make_sound()
cat.info()

출력:

Meow!
I am Whiskers, a sneaky cat

핵심 포인트: 메서드 오버라이딩(Method overriding)을 사용하면 자식 클래스가 상속받은 동작을 원하는 대로 수정할 수 있습니다. 자식 클래스에서 동일한 이름의 메서드를 정의하기만 하면 됩니다. 그러면 부모의 버전 대신 자식의 버전이 사용됩니다.

challenge icon

챌린지

중급

이 챌린지에서는 도형 계층 구조를 구현합니다.

  • shape.py - color 속성과 메서드를 가진 부모 Shape 클래스를 포함합니다
  • circle.py - Shape를 상속받는 Circle 클래스를 포함합니다
  • square.py - Shape를 상속받는 Square 클래스를 포함합니다

각 파일에는 구현 과정을 단계별로 안내하는 상세한 TODO 주석이 포함되어 있습니다.

치트 시트

메서드 오버라이딩(Method overriding)을 사용하면 자식 클래스가 부모 클래스에 이미 존재하는 메서드에 대해 자체적인 구현을 제공할 수 있습니다.

부모 클래스 예시:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

메서드를 오버라이딩하는 자식 클래스:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")  # 부모 메서드를 오버라이딩합니다

Dog의 make_sound 메서드는 Animal의 메서드를 대체하지만, info는 여전히 변경되지 않은 상태로 상속됩니다.

여러 메서드를 오버라이딩할 수 있습니다:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

핵심 포인트: 자식 클래스에서 동일한 이름의 메서드를 정의하기만 하면 됩니다. 그러면 부모의 버전 대신 자식의 버전이 사용됩니다.

직접 해보기

from shape import Shape
from circle import Circle
from square import Square

# 테스트 케이스 처리기
test_case = input()

if test_case == "base_shape":
    # 기본 Shape 클래스 테스트
    shape = Shape("green")
    print(f"Color: {shape.color}")
    print(f"Area: {shape.area()}")
    print("Describe output:")
    shape.describe()

elif test_case == "circle_basics":
    # Circle 생성 및 기본 메서드 테스트
    circle = Circle("red", 5)
    print(f"Color: {circle.color}")
    print(f"Radius: {circle.radius}")
    print(f"Area (rounded): {round(circle.area(), 2)}")
    print("Describe output:")
    circle.describe()

elif test_case == "square_basics":
    # Square 생성 및 기본 메서드 테스트
    square = Square("blue", 4)
    print(f"Color: {square.color}")
    print(f"Side length: {square.side_length}")
    print(f"Area: {square.area()}")
    print("Describe output:")
    square.describe()

elif test_case == "various_sizes":
    # 다양한 크기의 여러 인스턴스 테스트
    shapes = [
        Circle("yellow", 2),
        Circle("orange", 7.5),
        Square("purple", 3),
        Square("black", 10)
    ]
    
    for i, shape in enumerate(shapes, 1):
        print(f"Shape {i}:")
        shape.describe()
        print(f"Area: {round(shape.area(), 2)}")
        print()  # 가독성을 위한 빈 줄

elif test_case == "shape_polymorphism":
    # 도형 리스트를 사용한 다형성 동작 테스트
    shapes = [
        Shape("white"),
        Circle("red", 3),
        Square("blue", 4)
    ]
    
    print("Polymorphic behavior demonstration:")
    for shape in shapes:
        shape.describe()
        print(f"Area: {round(shape.area(shape_polymorphism), 2)}")
        print()  # 가독성을 위한 빈 줄

elif test_case == "original_test_case":
    # 챌린지의 원본 테스트 코드 실행
    circle = Circle("red", 5)
    square = Square("blue", 4)

    # describe 메서드 테스트
    circle.describe()
    square.describe()

    # area 메서드 테스트
    print(f"Circle area: {circle.area()}")
    print(f"Square area: {square.area()}")
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Object Oriented Programming의 모든 레슨