본문 바로가기
Python

파이썬 상속 예제

by 헬로제이콥 2025. 5. 14.

다음은 제공해주신 Person 클래스를 상속받는 Student 클래스를 정의한 간단한 파이썬 상속 예제입니다.

Python
 
# 부모 클래스 Person 정의
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def introduce(self):
    print(f"제 이름은 {self.name}이고, 나이는 {self.age}살입니다.")

# Person 클래스를 상속받는 자식 클래스 Student 정의
class Student(Person):
  def __init__(self, name, age, student_id):
    # 부모 클래스의 __init__ 메서드 호출
    super().__init__(name, age)
    self.student_id = student_id

  def study(self):
    print(f"학생 {self.name}(이)가 공부하고 있습니다. (학번: {self.student_id})")

# Person 객체 생성 및 메서드 호출
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
p1.introduce()

print("-" * 20) # 구분선

# Student 객체 생성 및 메서드 호출
s1 = Student("Alice", 20, "2023001")
print(s1.name)       # 부모 클래스로부터 상속받은 속성
print(s1.age)        # 부모 클래스로부터 상속받은 속성
print(s1.student_id) # Student 클래스 고유의 속성
s1.introduce()     # 부모 클래스로부터 상속받은 메서드
s1.study()         # Student 클래스 고유의 메서드

코드 설명:

  1. class Person::
    • __init__(self, name, age): 이름(name)과 나이(age)를 초기화하는 생성자입니다.
    • introduce(self): 사람을 소개하는 메시지를 출력하는 메서드입니다.
  2. class Student(Person)::
    • Student(Person): Student 클래스가 Person 클래스를 상속받음을 의미합니다. Student는 Person의 모든 속성과 메서드를 물려받습니다.
    • __init__(self, name, age, student_id):
      • super().__init__(name, age): 부모 클래스(Person)의 __init__ 메서드를 호출하여 name과 age를 초기화합니다.
      • self.student_id = student_id: Student 클래스에만 있는 학번(student_id) 속성을 초기화합니다.
    • study(self): 학생이 공부한다는 메시지를 출력하는 Student 클래스 고유의 메서드입니다.

실행 결과:

John
36
제 이름은 John이고, 나이는 36살입니다.
--------------------
Alice
20
2023001
제 이름은 Alice이고, 나이는 20살입니다.
학생 Alice(이)가 공부하고 있습니다. (학번: 2023001)

이 예제에서 Student 클래스는 Person 클래스의 name, age 속성과 introduce 메서드를 그대로 사용할 수 있으며, 추가적으로 student_id 속성과 study 메서드를 가집니다. 이것이 바로 상속의 기본적인 개념입니다.