다중 상속

Python 중급 객체 지향 프로그래밍

Jake Roach

Data Engineer

다중 상속

하나의 클래스가 둘 이상의 클래스 기능을 상속 가능

  • InternEmployeeStudent 둘 다에서 상속
  • "is-a" 관계 유지

Intern 클래스가 Employee와 Student 클래스를 상속.

class Employee:
  def __init__(self, department):
    self.department = department

  def begin_job(self):
    print(f"Welcome to {self.department}!")
class Student:
  def __init__(self, school):
    self.school = school
    self.courses = []

  def add_course(self, course_name):
    self.courses.append(course_name)
Python 중급 객체 지향 프로그래밍

다중 상속

class Intern(Employee, Student):
    def __init__(self, department, school, duration):
        # 두 생성자 모두 호출
        Employee.__init__(self, department)
        Student.__init__(self, school)
        self.duration = duration

    def onboard(self, mentor):
        # 새 메서드 구현
        ...
Python 중급 객체 지향 프로그래밍

Intern 객체 생성

stephen = Intern("Software Development", "Echo University", 10)
stephen.begin_job()  # Employee의 메서드
Welcome to Software Development!
stephen.add_course("Intermediate OOP in Python")  # Intern의 메서드
print(stephen.courses)
["Intermediate OOP in Python"]
Python 중급 객체 지향 프로그래밍

다단계 상속

다른 클래스를 상속하는 클래스를 다시 상속하여 손자 클래스가 됨

  • "is-a" 관계 유지

다단계 상속을 보여주는 그래픽.

class Person:
  def __init__(self, name):
    self.name = name

  def introduce(self):
      print(f"Hello, my name is {self.name}")
class Employee(Person):
  def __init__(self, name, title):
    Person.__init__(self, name)
    self.title = title

  def change_position(self, new_title):
    print(f"Starting new role as {new_title}")
    self.title = new_title
Python 중급 객체 지향 프로그래밍

다단계 상속

class Manager(Employee):
  def __init__(self, name, title, number_reports):
    Employee.__init__(self, name, title)
    self.number_reports = number_reports

    mike = Manager("Mike", "Engineering Manager", 14)
mike.introduce()
mike.change_position("Director of Engineering")
print(mike.number_reports)
Hello, my name is Mike
Starting new role as Director of Engineering
14
Python 중급 객체 지향 프로그래밍

메서드 결정 순서(MRO)

부모와 자식이 같은 이름의 메서드를 구현하면, Python이 사용할 메서드를 결정하는 순서

MRO 결정 규칙:

  • 자식 클래스를 먼저 탐색
  • 부모 클래스는 선언된 순서대로 좌→우 탐색

$$

.mro() 메서드와 __mro__

여러 부모 클래스를 상속하는 자식 클래스.

1 Beyond the Basic Stuff with Python, Sweigart (p. 311)
Python 중급 객체 지향 프로그래밍

메서드 결정 순서(MRO)

class Intern(Employee, Student):  # Intern은 Employee와 Student 클래스를 상속
  ...

# Intern의 MRO 확인
print(Intern.mro())
[<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>]
# __mro__로 MRO 확인
print(Intern.__mro__)
(<class '__main__.Intern'>, <class '__main__.Employee'>, <class '__main__.Student'>, <class 'object'>)
Python 중급 객체 지향 프로그래밍

연습해 봅시다!

Python 중급 객체 지향 프로그래밍

Preparing Video For Download...