본문 바로가기
IT/Python Quiz

[python] 클래스 상속 코드 작성 연습

by Echinacea 2025. 2. 19.
반응형

 

문제 1

부모 클래스 Animal을 상속받는 Dog 클래스를 작성하세요. Dog 클래스는 bark() 메서드를 추가하여 "멍멍"을 출력해야 합니다.

🔹 예시

class Animal:
    def speak(self):
        print("소리를 냅니다.")

🔹 출력 예시

d = Dog()
d.speak()  # "소리를 냅니다."
d.bark()   # "멍멍"

 

 

문제 2

Vehicle 클래스를 상속받아 Car 클래스를 작성하세요. Car 클래스는 drive() 메서드를 추가하여 "자동차가 달립니다."를 출력해야 합니다.

🔹 예시

class Vehicle:
    def move(self):
        print("이동 중입니다.")

🔹 출력 예시

c = Car()
c.move()  # "이동 중입니다."
c.drive() # "자동차가 달립니다."

 

 

문제 3

부모 클래스 Person을 상속받아 Student 클래스를 만들고, study() 메서드를 추가하여 "공부 중입니다."를 출력하세요.

🔹 예시

class Person:
    def greet(self):
        print("안녕하세요.")

🔹 출력 예시

s = Student()
s.greet()  # "안녕하세요."
s.study()  # "공부 중입니다."

 

 

문제 4

Bird 클래스를 상속받아 Eagle 클래스를 작성하세요. Eagle 클래스는 fly() 메서드를 추가하여 "독수리가 날아갑니다."를 출력해야 합니다.

🔹 예시

class Bird:
    def sound(self):
        print("짹짹")

🔹 출력 예시

e = Eagle()
e.sound()  # "짹짹"
e.fly()    # "독수리가 날아갑니다."

 

 

문제 5

부모 클래스 Shape를 상속받아 Rectangle 클래스를 작성하고, area() 메서드를 추가하여 사각형의 넓이를 계산하세요.

🔹 예시

class Shape:
    def describe(self):
        print("이것은 도형입니다.")

🔹 출력 예시

r = Rectangle(5, 10)
r.describe()   # "이것은 도형입니다."
print(r.area())  # 50

 

 

 

 

 

 

 

 

 

 

✅ 정답

문제 1 정답

class Dog(Animal):
    def bark(self):
        print("멍멍")

문제 2 정답

class Car(Vehicle):
    def drive(self):
        print("자동차가 달립니다.")

문제 3 정답

class Student(Person):
    def study(self):
        print("공부 중입니다.")

문제 4 정답

class Eagle(Bird):
    def fly(self):
        print("독수리가 날아갑니다.")

문제 5 정답

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height

 

반응형

댓글