조합과 상속
도입됨이 수업의 내용
| English | 의미 |
|---|---|
| inheritance/ɪnˈherɪtəns/ | 상속 |
| composition/ˌkɒmpəˈzɪʃn/ | 조합 |
| fragile base class/ˈfrædʒaɪl beɪs klæs/ | 취약한 베이스 클래스 |
One fix, a thousand wrong receipts
- A shop adds a loyalty bonus to its receipt total. The next day every discount receipt is wrong, though nobody touched the discount code.
- The discount class had copied the old total code instead of reusing it. How classes connect decides whether a fix in one place stays a fix everywhere.
Two ways to connect classes
- Inheritance 继承 says is-a: a
Memberis aPerson. Composition 组合 says has-a: aLibraryhas aCatalog. - Inheritance ties classes tightly. When a change to a base class breaks its children, that is the fragile base class 脆弱基类 problem.
super() builds the base first
super().__init__(...)runs the base class's set-up first, soPerson.__init__finishes before anyMemberline runs. Skip it andself._namedoes not exist whenMemberneeds it.
class Member(Person):
def __init__(self, name, card):
super().__init__(name)
self._card = card
self._loans = 0
Member.__init__은 super().init(name)로 시작하므로 —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
체인은 기본 클래스부터 시작하므로: super()를 건너뛰면 Member가 필요할 때 self._name이 아직 존재하지 않습니다.
Member('Ana', 7)의 단계 순서를 정리하십시오.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
베이스는 항상 먼저 생성되므로, Member는 _name에 의존할 수 있습니다.
Override by delegating
- To change a base method, call it and adjust the result:
return super().total() - 10. The base's loyalty bonus then stays in your total. - Copying the base's code into the override makes a fork. The day the base gains a line, the copy goes stale: that was the receipt bug.
class Receipt:
def total(self):
# the new loyalty line
t = sum(self.prices)
return t - self.bonus()
# Bug: copied, so no bonus
class DiscountReceipt(Receipt):
def total(self):
return sum(self.prices) - 10
# Fix: delegate to the base
class DiscountReceipt(Receipt):
def total(self):
return super().total() - 10
베이스 메서드 본체를 복사하는 오버라이드 —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
복사된 코드는 포크입니다: 베이스는 계속 변경되지만 사본은 그대로 두어 방치됩니다.
Receipt.total()이 100를 반환했습니다. 이후 기본 클래스에 loyalty 줄이 추가되어 5만큼 감소합니다. DiscountReceipt.total()은 super().total() − 10로 정의됩니다. 이제 이 함수는 어떤 값을 반환합니까?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
베이스는 현재 95을 제공하며, 오버라이드는 이 값에서 10을 뺍니다. 복사된 본체라면 여전히 90을 표시할 것입니다.
Composition delegates
- A
Libraryholds itsCopyobjects and passes questions on:available()asks each partnot c.is_out()and counts the answers. - The library holds no borrowing logic of its own. Each part keeps its own rules.

Library와 그 Catalog는 다음 중 하나로 연결하는 것이 가장 좋습니다 —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Has-a는 조합입니다: 전체가 부품을 소유하고 호출을 전달하며, 부품을 교체해도 인터페이스는 유지됩니다.
Swap the part, keep the whole
- Replace the list of copies with a database-backed collection and
Librarydoes not change: parts change, the whole keeps its interface. - Rule of thumb: inheritance for a true is-a, composition for everything else.
Library 클래스는 list를 상속하여 복사본을 저장할 수 있도록 해야 합니다
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
도서관에는 복사본이 있지만, list가 아닙니다. 조합은 list를 교체 가능하게 유지하고 도서관에서 제공해서는 안 되는 list 메서드를 숨깁니다
Worked example: building and counting
Member('Ana', 7)startsMember.__init__, which callsPerson.__init__('Ana')to set_name; then_card = 7and_loans = 0. Twoborrow()calls make_loans2.- A library gets 5 copies and 2 are issued:
available()asks all 5 and returns 3.
도서관은 8개의 복사본을 보유합니다. 3개가 대출되었으며, 그중 1개는 반납되었습니다. available()의 반환값은 무엇입니까?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
2 부가 아직 판매 중이므로, 8 − 2 = 6 부를 구매할 수 있습니다.
Three common slips
- Inheriting just to reuse two methods. Use composition or a plain function.
- Forgetting
super().__init__. The base's attributes then never exist. - Copying base code into an override. The fork goes stale; delegate with
super().
Recap
| Inheritance | Composition | |
|---|---|---|
| Says | is-a: a Member is a Person |
has-a: a Library has a Catalog |
| Ties classes | tightly | loosely |
| Rule | call super() so the base is built first |
delegate questions to the parts |
- Override by calling the base, never by copying it.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.