다중 상속
Coddy Python 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 64개 중 20번째.
다중 상속을 사용하면 클래스가 둘 이상의 부모 클래스로부터 상속을 받을 수 있어, 여러 소스의 기능을 결합할 수 있습니다.
다음은 두 개의 부모 클래스입니다:
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} is eating"
class Flyable:
def fly(self):
return f"{self.name} is flying"두 부모 클래스로부터 상속받는 자식 클래스를 생성합니다:
class Bird(Animal, Flyable):
def __init__(self, name, species):
super().__init__(name) # Animal의 __init__을 호출합니다
self.species = species
def sing(self):
return f"{self.name} is singing"class Bird(Animal, Flyable): 구문은 Bird가 Animal과 Flyable 모두로부터 상속받는다는 것을 의미합니다.
bird 객체를 생성하고 두 부모의 메서드를 사용합니다:
sparrow = Bird("Sparrow", "House sparrow")첫 번째 부모 클래스의 메서드를 호출합니다:
print(sparrow.eat())두 번째 부모 클래스의 메서드를 호출합니다:
print(sparrow.fly())새 자신의 메서드를 호출합니다:
print(sparrow.sing())출력:
Sparrow is eating
Sparrow is flying
Sparrow is singing상속 순서를 확인할 수 있습니다:
print(Bird.__mro__) # 메서드 결정 순서이것은 메서드를 찾을 때 어떤 부모가 먼저 확인되는지를 보여줍니다.
핵심 포인트: 다중 상속은 class Child(Parent1, Parent2): 구문을 사용합니다. 자식 클래스는 모든 부모 클래스로부터 모든 메서드를 상속받습니다. 파이썬은 메서드를 찾을 때 부모 클래스를 왼쪽에서 오른쪽 순서로 확인합니다.
챌린지
중급이 챌린지에서는 스마트폰을 사용하여 다중 상속을 보여주는 다중 파일 클래스 시스템을 구현합니다. 각 클래스는 더 나은 코드 구성을 위해 자체 파일로 구성되어 있습니다.
다음 파일들을 수정해야 합니다:
device.py-Device기본 클래스를 구현합니다.internet.py-Internet기본 클래스를 구현합니다.smartphone.py- 두 기본 클래스를 모두 상속받는Smartphone클래스를 구현합니다.driver.py- 구현이 올바르게 작동하는지 확인하는 테스트 케이스를 구현합니다.
각 파일에는 구현 과정을 단계별로 안내하는 상세한 TODO 주석이 포함되어 있습니다.
치트 시트
다중 상속을 사용하면 class Child(Parent1, Parent2): 구문을 사용하여 클래스가 둘 이상의 부모 클래스로부터 상속받을 수 있습니다.
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} is eating"
class Flyable:
def fly(self):
return f"{self.name} is flying"
class Bird(Animal, Flyable):
def __init__(self, name, species):
super().__init__(name) # Animal의 __init__을 호출합니다
self.species = species
def sing(self):
return f"{self.name} is singing"자식 클래스는 모든 부모 클래스로부터 모든 메서드를 상속받습니다:
sparrow = Bird("Sparrow", "House sparrow")
print(sparrow.eat()) # Animal 클래스로부터
print(sparrow.fly()) # Flyable 클래스로부터
print(sparrow.sing()) # Bird 자체 메서드어떤 부모가 먼저 확인되는지 보려면 메서드 결정 순서(Method Resolution Order, MRO)를 확인하세요:
print(Bird.__mro__) # 상속 순서를 보여줍니다직접 해보기
# TODO: smartphone.py에서 Smartphone 클래스를 가져오세요
# 스마트폰을 생성하고 메서드를 테스트합니다
# TODO: 브랜드가 "Apple"이고 모델이 "iPhone 13"인 Smartphone 객체를 생성하세요
my_phone = None
# TODO: 스마트폰의 power_on() 메서드를 호출하고 출력하세요
# TODO: 스마트폰의 connect() 메서드를 호출하고 출력하세요
# TODO: 매개변수 "123-456-7890"을 사용하여 스마트폰의 make_call() 메서드를 호출하고 출력하세요이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.