다형성
고급 객체 지향 프로그래밍 개념을 살펴봅니다.
다형성은(는) CoddyKit의 무료 Python For Kids 강의입니다. 이것은 5개 중 5번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python For Kids 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python For Kids 강의에는 총 5개의 강의가 포함되어 있습니다.
다형성
객체 지향 프로그래밍(OOP) 레슨에 다시 오신 것을 환영합니다! 오늘은 객체가 여러 형태를 취할 수 있도록 하는 강력한 개념인 Python의 다형성에 대해 알아보겠습니다.

다형성이란 무엇인가요?
다형성은 OOP의 핵심 개념으로, 서로 다른 클래스의 객체를 공통 부모 클래스의 객체처럼 다룰 수 있게 합니다. 또한 객체가 호출하는 대상에 따라 동일한 method가 다르게 동작하도록 합니다.
- 정의: "여러 형태"를 의미하며, 서로 다른 객체가 동일한 method 호출에 고유한 방식으로 응답하는 기능입니다.
- 목적: 서로 바꾸어 사용할 수 있는 객체를 허용하여 코드의 유연성과 통합성을 높입니다.
Python에서 다형성이 어떻게 동작하는지 살펴보겠습니다!
다형성 구현하기
Python에서는 method 재정의와 서로 다른 객체 유형에서 작동하는 내장 함수를 사용하여 다형성을 구현할 수 있습니다.
- Method 재정의: 부모 클래스에 이미 정의된 method를 자식 클래스에서 다시 정의하는 것입니다.
- 내장 함수: 다양한 데이터 유형에서 작동하는
len()과 같은 함수입니다.
method 재정의를 자세히 살펴보겠습니다.
Method 재정의
Method 재정의를 사용하면 자식 클래스가 부모 클래스에 이미 정의된 method에 대한 구체적인 구현을 제공할 수 있습니다. 이는 다형성의 핵심 요소입니다.
예제:
# Defines the Animal parent class with a speak method
class Animal:
def speak(self):
print("The animal makes a sound.") # Generic speak method
재정의된 Methods를 사용하는 자식 클래스 만들기
Animal을 상속하고 speak method를 재정의하여 구체적인 동작을 제공하는 자식 클래스를 만들어 보겠습니다.
예제:
# Defines the Dog child class inheriting from Animal
class Dog(Animal):
def speak(self):
print("The dog barks.") # Overridden speak method
# Defines the Cat child class inheriting from Animal
class Cat(Animal):
def speak(self):
print("The cat meows.") # Overridden speak method
재정의된 Methods로 다형성 사용하기
이제 자식 클래스의 객체를 만들고 동일한 method 이름을 사용하면서 서로 다른 동작을 나타내는지 살펴보겠습니다.
예제:
# Creates objects of Dog and Cat classes
dog = Dog()
cat = Cat()
# Calls the speak method on both objects
dog.speak() # Output: The dog barks.
cat.speak() # Output: The cat meows.
내장 함수와 다형성
다형성은 사용자가 정의한 클래스에만 한정되지 않습니다. len()과 같은 Python의 내장 함수는 서로 다른 데이터 유형에서 작동하며 다형성 동작을 보여 줍니다.
예제:
# Uses len() with a list
my_list = [1, 2, 3, 4]
print(len(my_list)) # Output: 4
# Uses len() with a string
my_string = "Hello"
print(len(my_string)) # Output: 5
# Uses len() with a dictionary
my_dict = {"a": 1, "b": 2}
print(len(my_dict)) # Output: 2
예제 프로그램: Shape 넓이 계산
다형성을 사용하여 서로 다른 도형의 넓이를 계산하는 프로그램을 만들어 보겠습니다. 부모 클래스 Shape와 area method를 재정의하는 자식 클래스 Circle, Rectangle을 정의하겠습니다.
코드:
# Defines the Shape parent class with an area method
class Shape:
def area(self):
pass # Placeholder method
# Defines the Circle child class inheriting from Shape
class Circle(Shape):
def __init__(self, radius):
self.radius = radius # Sets the radius of the circle
def area(self):
return 3.14 * self.radius ** 2 # Calculates area of the circle
# Defines the Rectangle child class inheriting from Shape
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width # Sets the width of the rectangle
self.height = height # Sets the height of the rectangle
def area(self):
return self.width * self.height # Calculates area of the rectangle
# Creates objects of Circle and Rectangle classes
circle = Circle(5)
rectangle = Rectangle(4, 6)
# Calculates and prints areas using polymorphism
print("Circle Area:", circle.area()) # Output: Circle Area: 78.5
print("Rectangle Area:", rectangle.area()) # Output: Rectangle Area: 24
# Defines the Vehicle parent class with a move method
class Vehicle:
def move(self):
print("The vehicle moves.")
# Defines the Bicycle child class inheriting from Vehicle
class Bicycle(Vehicle):
def move(self):
print("The bicycle pedals forward.")
# Defines the Airplane child class inheriting from Vehicle
class Airplane(Vehicle):
def move(self):
print("The airplane flies in the sky.")
# Creates objects of Bicycle and Airplane classes
bike = Bicycle()
plane = Airplane()
# Calls the move method on both objects
bike.move()
plane.move()
잘하셨습니다!
Python의 다형성과 이를 통해 서로 다른 클래스의 객체가 동일한 method 호출에 고유한 방식으로 응답하는 방법을 학습하셨습니다. 다형성은 코드의 유연성과 확장성을 높여 코드를 더 쉽게 관리하고 확장할 수 있게 합니다. 다형성 동작을 활용하는 클래스와 methods를 더 만들어 보며 이해를 더욱 깊게 해 보세요!

자주 묻는 질문
“다형성” 강의는 무료인가요?
네 — “다형성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python For Kids 강의 전체를 잠금 해제할 수 있습니다. Python For Kids 강의에는 총 5개의 강의가 포함되어 있습니다.
“다형성”에서 뭘 배우나요?
고급 객체 지향 프로그래밍 개념을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Python For Kids을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Python For Kids을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Python For Kids은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 5개 중 5번째 강의입니다.
“다형성” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Python For Kids 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Python For Kids 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.