인터페이스와 다형성
도입됨
5:16
객체 지향 프로그래밍
This course is about how a small script grows into a system that other people can safely change. The first two units build the object: classes, references and…
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| interface/ˈɪntəfeɪs/ | 인터페이스 |
| polymorphism/ˈpɒlɪmɔːfɪzəm/ | 다형성 |
| duck typing/dʌk ˈtaɪpɪŋ/ | 오리 타입 |
| runtime type/ˈrʌntaɪm taɪp/ | 러닝타임 타입 |
| dynamic dispatch/daɪˈnæmɪk dɪˈspætʃ/ | 동적 디스패치 |
| open/closed/ˈəʊpən kləʊzd/ | 개방/폐쇄 원칙 |
| substitution/ˌsʌbstɪˈtjuːʃn/ | 대체성 |
Email today, SMS tomorrow
- The library sends due-date reminders by email. Next term it adds SMS, and later a message queue for another app.
- If the reminder code names each class, it must change every time. If it names only the behaviour "send", it never changes.
Name the behaviour
- An interface 接口 names what a thing does (
send), not which class it is. - Polymorphism 多态 is one call site running many implementations:
n.send(text)works for every kind of sender.
Duck typing and Protocol
- Python is dynamically typed: any object with the right methods fits. This is duck typing 鸭子类型.
- A
Protocolwrites the contract down without forcing inheritance, so tools can check it.
class Notifier(Protocol):
def send(self, text: str) -> str: ...
프로토콜의 명칭 —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
구조적 계약입니다: 명시된 메서드를 가진 모든 객체가 적합하며, 상속은 필요 없습니다.
Notifier 프로토콜이 요구되는 지점에서, 클래스는 Notifier에서 상속받아야 합니다.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
프로토콜은 구조적입니다. send 메서드가 일치하는 모든 클래스가 적합하며, 상속은 필요 없습니다.
Dispatch follows the object
- When
n.send('loan due')runs, Python looks upsendon the runtime type 运行时类型: the class of the object, not the variable's annotation. - This is dynamic dispatch 动态绑定: the call is written once, and the method is chosen for each object at call time.

SmsNotify()를 저장하는 변수가 n.send(due)를 실행하면: 호출은 — 으로 전달됩니다
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
동적 디스패치는 어노테이션이 아닌 변수가 보유한 객체에 대해 해결됩니다.
각 용어를 그 의미와 매칭하십시오.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
두 요소가 결합되어 호출자가 클래스가 아닌 행동에 의존할 수 있게 합니다.
n.send('loan due') 호출의 단계를 순서대로 나열하십시오.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
변수의 주석은 역할을 하지 않으며, 객체가 결정합니다.
Open to new types
- Adding a fourth sender class touches no existing line: the caller was never told the concrete classes.
- This is the open/closed 开闭 idea: open to new types, closed to editing.
리마인더 루프는 세 개의 sender 클래스와 함께 작동합니다. 네 번째 sender 클래스가 작성되었습니다. 루프 내부에서 변경해야 할 줄은 몇 줄입니까?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
루프는 오직 n.send만 호출합니다. 새 클래스는 목록에 추가되지만, 루프 자체는 수정에 대해 열려 있습니다.
Substitution is a promise
- Substitution 替换 (the Liskov rule): every implementation must accept at least what the interface promises and keep every guarantee. Preconditions may only widen; guarantees may only grow.
- A
SilentNotify.sendthat raises on an empty string narrows the contract. It breaks a caller who was told thatsendnever raises.
대안 구현은 —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
교체: 약속된 것을 적어도 받아들이고, 약속을 깨뜨리지 마십시오.
Replace isinstance chains
- A chain like
if isinstance(n, EmailNotify): ... elif isinstance(n, SmsNotify): ...must be edited for every new type. - Give each class its own method instead and let dispatch choose. That is what polymorphism is for.
Worked example: one loop, three senders
team = [EmailNotify(), SmsNotify(), QueueNotify()], thenfor n in team: print(n.send('loan due')).- Output:
email: loan due,sms: loan due,queue: loan due. Three classes, one call site, noif.
Three common slips
- Writing
isinstancechains. Each new type means another edit; use a method per class. - Adding a precondition in an override. Callers who trusted the interface break.
- Thinking the annotation picks the method. The object's runtime type does.
Recap
- An interface names behaviour; a Protocol writes it down; duck typing lets any fitting object in.
- Dynamic dispatch picks the method from the runtime type, so new types need no caller edits.
| Term | Means |
|---|---|
| Interface | what a thing does: send |
| Polymorphism | one call site, many implementations |
| Duck typing | any object with the right methods fits |
| Open/closed | add new types without editing old code |
| Liskov substitution | every implementation keeps the whole contract |
- Substitutes must honour the whole contract: widen inputs, keep every guarantee.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.