Python - 문제 미리보기

문제 2063

medium
다음 클래스 다형성 코드의 실행 결과는? ```python class Dog: def make_sound(self): return "멍멍!" class Cat: def make_sound(self): return "야옹!" class Bird: def make_sound(self): return "짹짹!" animals = [Dog(), Cat(), Bird()] for animal in animals: print(animal.make_sound()) ```
A. 멍멍!, 야옹!, 짹짹!
B. make_sound, make_sound, make_sound
C. Dog, Cat, Bird
D. 오류 발생

정답: A

클래스 다형성의 실제 구현: 다형성의 핵심 원리: ⦁ 통일된 인터페이스: 모든 클래스가 같은 메서드명 `make_sound()` 사용 ⦁ 다른 구현: 각 클래스마다 메서드 내용이 다름 ⦁ 일관된 호출: 같은 방식으로 호출하지만 결과는 다름 단계별 실행 과정: 1. 객체 생성: ```python animals = [Dog(), Cat(), Bird()] # 서로 다른 클래스의 객체들을 하나의 리스트에 저장 ``` 2. 반복문 실행: ```python for animal in animals: print(animal.make_sound()) ``` 첫 번째 반복 (`Dog` 객체): ⦁ `animal = Dog()` 인스턴스 ⦁ `animal.make_sound()` → `Dog.make_sound()` 호출 ⦁ 출력: "멍멍!" 두 번째 반복 (`Cat` 객체): ⦁ `animal = Cat()` 인스턴스 ⦁ `animal.make_sound()` → `Cat.make_sound()` 호출 ⦁ 출력: "야옹!" 세 번째 반복 (`Bird` 객체): ⦁ `animal = Bird()` 인스턴스 ⦁ `animal.make_sound()` → `Bird.make_sound()` 호출 ⦁ 출력: "짹짹!"

💡 학습 팁

이 문제를 포함한 Python 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.