接口与多态
引入
5:16
面向对象编程
这门课讲的是一个小脚本如何成长为一个其他人可以安全修改的系统。前两个单元构建对象:类、引用和封装的保护墙。接下来的两个单元通过组合、继承和接口将对象连接起来。最后两个单元用异常和测试维持系统的运行。每个类都是它与调用者之间的一份契约。
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| interface/ˈɪntəfeɪs/ | 接口 | jiē kǒu |
| polymorphism/ˈpɒlɪmɔːfɪzəm/ | 多态 | duō tài |
| duck typing/dʌk ˈtaɪpɪŋ/ | 鸭子类型 | yā zi lèi xíng |
| runtime type/ˈrʌntaɪm taɪp/ | 运行时类型 | yùn xíng shí lèi xíng |
| dynamic dispatch/daɪˈnæmɪk dɪˈspætʃ/ | 动态绑定 | dòng tài bǎng dìng |
| open/closed/ˈəʊpən kləʊzd/ | 开闭 | kāi bì |
| substitution/ˌsʌbstɪˈtjuːʃn/ | 替换 | tì huà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.
提醒循环使用三个发送器类。现编写第四个发送器类。循环内部必须更改多少行代码?
难度 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.
出了什么问题?只有网站团队能看到这些信息。