B3.2.3 · Fundamentals of OOP for multiple classes (HL)
B3.2.3 · 多个类的 OOP 基础(HL)
Abstraction and abstract classes
抽象与抽象类
Writing down what every subclass must be able to do, without pretending to know how any of them will do it.
写下每个子类都必须能做什么,而不假装知道其中任何一个会怎么做。
Explainer
讲解
Lansdown Vehicle Hire rents out cars, vans, motorcycles and trucks. Every booking screen has to show two things: what it costs per day, and what category of licence the driver needs to be allowed to drive it. Neither has a generic answer. A motorcycle is category A, a car or van is B, a truck is C, and the daily rates are nowhere near each other. Inventing a default would not merely be untidy: it would quote the wrong price, or hand a truck to someone licensed only for a car.
Lansdown 汽车租赁公司出租轿车、货车、摩托车和卡车。每个预订界面都要显示两样东西:每天的费用,以及驾驶员需要哪一类驾照才被允许驾驶它。这两者都没有通用的答案。摩托车是 A 类,轿车或面包车是 B 类,卡车是 C 类,而且日租金相差甚远。凭空设一个默认值不仅不整洁:它会报出错误的价格,或者把卡车交给只持有轿车驾照的人。
Abstraction is the practice of exposing only the essential features of something while keeping the details of how it works out of sight. In OOP it means designing around what an object can be asked to do, rather than around how any particular object does it.
抽象(abstraction)是指只暴露某样东西的基本特征,而把它如何工作的细节隐藏起来。在 OOP 中,它意味着围绕对象可以被要求做什么来设计,而不是围绕某个具体对象怎么做。
An abstract class is a class that cannot be instantiated on its own. It exists to be inherited from. It may declare abstract methods, which have a name and a signature but no body, and which every concrete subclass is obliged to implement.
抽象类是一个不能独立被实例化的类。它的存在就是为了被继承。它可以声明抽象方法,抽象方法只有名字和签名,没有方法体,每一个具体的子类都必须实现它。
Together these give the hire firm exactly what it needs: a written guarantee that every vehicle type, including ones nobody has added yet, can answer "what do you cost?" and "what licence do you need?", without the booking screen knowing a single thing about cars, motorcycles or trucks.
这两者合在一起,正好给了租赁公司所需要的东西:一份书面保证,即每一种车辆类型,包括还没有人添加的类型,都能回答"你的费用是多少?"和"需要什么驾照?",而预订界面完全不必知道轿车、摩托车或卡车的任何事情。
Explainer
讲解
The test for when an abstract class is the right choice
什么时候抽象类是正确的选择:判断标准
Not every parent class should be abstract. The deciding question is short, and it is the one examiners reward:
并不是每个父类都应该是抽象的。判断的问题很简短,而且也是考官会给分的那一个:
Every subclass must have this method, and there is no sensible default implementation you could write for it. If you can write a reasonable default, use a normal class and let subclasses override it. If any default you could write would be a guess, make the method abstract and force each subclass to supply its own.
每个子类都必须有这个方法,而且你写不出任何合理的默认实现。如果你能写出一个合理的默认实现,就用普通的类,让子类去重写它。如果你能写出的任何默认实现都只是猜测,就把这个方法设为抽象,强制每个子类提供自己的实现。
Applied at Lansdown: licence_category() has no defensible default, so it is abstract. hire_summary() is the same sentence for every vehicle, so it is written once as a normal method and inherited. One abstract class can hold both kinds at once, which is a point worth stating explicitly in an answer.
应用到 Lansdown:licence_category() 没有站得住脚的默认值,所以是抽象的。hire_summary() 对每辆车都是同一句话,所以作为普通方法写一次并被继承。一个抽象类可以同时包含这两种方法,这一点值得在答案中明确说出来。
Worked example
例题讲解
The contract, in code
用代码表示的契约
daily_rate()
Declared, never implemented here. Every concrete subclass must supply its own, because a rate that suits a motorcycle would badly undercharge a truck.
只声明,在这里从不实现。每个具体的子类都必须提供自己的实现,因为适合摩托车的费率,对卡车会严重少收费。
licence_category()
Same reasoning, with a legal edge: guessing this wrong hands a vehicle to a driver who is not entitled to drive it.
同样的道理,而且还带有法律层面的后果:这里猜错,会把车辆交给一个无权驾驶它的驾驶员。
hire_summary()
Written once and inherited by all. It calls the two methods above without knowing or caring which subclass will answer.
只写一次,所有子类继承。它调用上面的两个方法,却不知道也不关心将由哪个子类来回答。
What is from abc import ABC, abstractmethod? Python has no abstract keyword, so unlike Java it cannot mark a class abstract in the language itself. The tools come from a module in the standard library instead, called abc, short for Abstract Base Class. Nothing needs installing, it ships with Python.
from abc import ABC, abstractmethod 是什么?Python 没有 abstract 关键字,所以不像 Java 那样,无法在语言层面把一个类标记为抽象。相关的工具来自标准库里的一个模块,叫 abc,是 Abstract Base Class(抽象基类)的缩写。不需要安装任何东西,它随 Python 自带。
The line brings in two separate things. ABC is a class to inherit from, and inheriting it is what makes your own class abstract. abstractmethod is a decorator, written on the line above a method, marking that method as one every concrete subclass is obliged to implement. You need both: ABC alone with no abstract methods would still be perfectly instantiable.
这一行引入了两个不同的东西。ABC 是一个可以继承的类,继承它就让你自己的类成为抽象类。abstractmethod 是一个装饰器,写在方法上面一行,把该方法标记为每个具体子类都必须实现的方法。两者都需要:只有 ABC 而没有抽象方法,类仍然完全可以被实例化。
from abc import ABC, abstractmethod class Vehicle(ABC): # inheriting ABC makes it abstract def __init__(self, reg, model): self.reg = reg self.model = model @abstractmethod def daily_rate(self): # no body: subclasses MUST write it pass @abstractmethod def licence_category(self): pass def hire_summary(self): # CONCRETE: shared by every vehicle return f"{self.reg} {self.model}: {self.daily_rate()} per day, licence {self.licence_category()}" class Car(Vehicle): def daily_rate(self): return 45 def licence_category(self): return "B"
abstract class Vehicle { // the abstract keyword does it here protected String reg; protected String model; public abstract int dailyRate(); // no body, ends with a semicolon public abstract String licenceCategory(); public String hireSummary() { // CONCRETE: shared by every vehicle return reg + " " + model + ": " + dailyRate() + " per day"; } } class Car extends Vehicle { @Override public int dailyRate() { return 45; } @Override public String licenceCategory() { return "B"; } }
Python has no abstract keyword. It uses the standard library instead: inherit from ABC and mark the required methods with @abstractmethod. Java has the keyword built into the language, and an abstract method is written with a semicolon where the body would go.
Python 没有 abstract 关键字。它使用标准库:继承 ABC,并用 @abstractmethod 标记必须实现的方法。Java 把这个关键字内置在语言中,抽象方法在本该写方法体的地方写一个分号。
Worked example
例题讲解
The two things an abstract class refuses
抽象类拒绝的两件事
This is what makes the contract real rather than a comment. Both of these are errors, caught before any wrong lorry is loaded.
这才让契约成为真正的约束,而不是一句注释。下面两种情况都是错误,在任何一辆错误的卡车被装上之前就被捕获了。
1. You cannot create one directly
1. 不能直接创建一个抽象类的对象
# Vehicle is a description, not a thing you can hire v = Vehicle("LV01 XYZ", "generic")
TypeError: Can't instantiate abstract class Vehicle with abstract methods daily_rate, licence_category
2. You cannot half-implement it
2. 不能只实现一半
# forgets licence_category() class Van(Vehicle): def daily_rate(self): return 65 v = Van("LV22 KLM", "Transit")
TypeError: Can't instantiate abstract class Van with abstract method licence_category
Notice when the second error appears: not when the incomplete class is defined, but the moment something tries to create one. The contract is checked at instantiation, which is still long before that van could reach a booking screen.
注意第二个错误出现的时间:不是在定义这个不完整的类时,而是在有东西试图创建它的对象的那一刻。契约是在实例化时检查的,这仍然远在那辆货车到达预订界面之前。
Explainer
讲解
Why this makes code more modular
为什么这会让代码更模块化
The first elaboration bullet asks specifically about modular code fragments, so it is worth being precise about what changes.
第一条拓展要点专门问到了模块化的代码片段,所以有必要准确说明发生了什么变化。
# the booking screen: it knows nothing about cars, motorcycles or trucks def show_fleet(vehicles): for v in vehicles: print(v.hire_summary())
This function depends on the abstract class alone, never on any concrete vehicle type. That has three consequences worth naming in an answer:
这个函数只依赖抽象类本身,从不依赖任何具体的车辆类型。这带来三个值得在答案里点出的后果:
The fragments can be written separately. One developer builds the booking screen while another writes Truck. Neither needs the other's code to exist, only the agreed contract.
各个片段可以分开编写。一位开发者做预订界面,另一位写 Truck。两者都不需要对方的代码已经存在,只需要双方约定好的契约。
They can be changed independently. Changing how a truck works out its daily rate cannot break the booking screen, because the screen only ever relied on the method existing and returning a value.
它们可以独立修改。修改卡车计算日租金的方式,不会破坏预订界面,因为界面始终只依赖这个方法存在并返回一个值。
A missing piece fails loudly and early. Without the abstract class, a vehicle that forgot licence_category() would only be discovered when a customer reached the checkout. With it, the object cannot be created at all.
缺失的部分会大声、尽早地失败。没有抽象类,一辆忘了写 licence_category() 的车辆,要等到顾客走到结账时才会被发现。有了抽象类,这个对象根本无法被创建。
Explainer
讲解
Abstract class, or an ordinary parent class?
抽象类,还是普通的父类?
Both give inheritance and shared code. Only one enforces anything.
两者都提供继承和共享代码。但只有一个会强制执行什么。
Real example: a Vehicle whose licence_category() returns "B" as a fallback, because most of the fleet is cars and vans.
实际例子:一个 Vehicle,它的 licence_category() 返回 "B" 作为后备,因为车队里大多数是轿车和面包车。
Advantage
优点
- Simpler, and usable on its own (a plain Vehicle object can be created for quick testing, with no subclass required)
- 更简单,而且可以单独使用 (可以直接创建一个普通的 Vehicle 对象来做快速测试,不需要任何子类)
Disadvantage
缺点
- A forgotten override fails silently (a new truck class that never defines licence_category() quietly inherits "B", so the system lets a car driver book a truck and nothing in the code complains)
- 忘记重写时会悄悄失败 (一个从未定义 licence_category() 的新卡车类,悄悄继承了 "B",于是系统允许一位轿车驾驶员预订卡车,而代码里没有任何地方报错)
Real example: the Vehicle(ABC) above, where licence_category() has no body at all.
实际例子:上面的 Vehicle(ABC),其中 licence_category() 根本没有方法体。
Advantage
优点
- The contract is enforced by the language (a subclass that forgets a required method cannot be instantiated, so the mistake surfaces immediately instead of becoming a wrongly licensed hire)
- 契约由语言来强制执行 (忘记写某个必需方法的子类无法被实例化,所以错误会立刻暴露,而不是变成一次驾照不符的租赁)
Disadvantage
缺点
- More rigid, and never usable alone (every subclass must implement every abstract method even when one of them has nothing meaningful to say, and the class itself can never be instantiated for testing)
- 更死板,而且永远不能单独使用 (每个子类都必须实现每一个抽象方法,即使其中某个方法根本没什么有意义的内容可说,而且这个类本身永远不能为了测试而被实例化)
Try it yourself
动手试试
Try to break the contract
试着打破这份契约
The Lansdown classes, live and editable. Two experiments: uncomment the line that tries to build a bare Vehicle, and the Van class that deliberately forgets licence_category(). Both should be refused.
Lansdown 的这些类,可在线编辑运行。两个实验:取消那行试图创建一个裸 Vehicle 的注释,以及那个故意忘记写 licence_category() 的 Van 类的注释。两者都应该被拒绝。
Running in offline fallback mode. The full Python engine couldn’t load (blocked school network, or no internet), so this console switched automatically to a small hand-written engine. It runs this page’s scenario, including ABC, @abstractmethod and the refusal to instantiate an incomplete class, but it isn’t full Python.
正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括 ABC、@abstractmethod 以及拒绝实例化不完整的类,但它不是完整的 Python。
Check your understanding
检查你的理解
Vehicle is abstract with one abstract method and one concrete method. Car extends it and implements the abstract method. Which statement is correct?
Vehicle 是抽象的,有一个抽象方法和一个具体方法。Car 继承它并实现了那个抽象方法。下列哪一项正确?
Common mistake
常见错误
B3.2.3B3.2.3 的这一常见模式RecurringCandidates claim an abstract class cannot contain any working code, describing it as a list of empty method names. An abstract class may hold concrete methods, attributes and a constructor; what it cannot do is be instantiated. Answers built on the stricter, wrong version lose marks even where the surrounding reasoning is good.
反复出现考生声称抽象类不能包含任何可运行的代码,把它描述成一串空的方法名。抽象类可以包含具体方法、属性和构造方法;它不能做的是被实例化。基于这种更严格、也是错误的说法所写的答案,即使其余推理很好,也会丢分。
The second error is choosing abstraction where plain inheritance would do. If a sensible default implementation exists, an ordinary parent class is the better design, and saying so demonstrates the judgment the command term is asking for.
第二个错误是在普通继承就够用的地方选择了抽象。如果存在合理的默认实现,普通的父类是更好的设计,并且说明这一点,正是指令词所要求的判断力。
Answer frame that scores: state that it cannot be instantiated → state what subclasses are obliged to provide → note that it may still supply shared concrete code.
能得分的答题框架:说明它不能被实例化 → 说明子类必须提供什么 → 指出它仍然可以提供共享的具体代码。
What a weak answer looks like: “An abstract class is an empty class containing only method names, which the subclasses then fill in.” The first half is wrong: hire_summary() is real, working, inherited code sitting inside an abstract class.
较弱的答案是这样的:“抽象类是一个空类,只包含方法名,由子类来填充。”前半句是错的:hire_summary() 是真实的、可运行的、被继承的代码,就放在一个抽象类里。
What it should say: “Vehicle cannot be instantiated. It declares licence_category() as abstract, so every concrete subclass must implement it, while still providing hire_summary() as working code that all vehicles inherit unchanged.” Instantiation, obligation, and shared code all stated.
应该这样写:“Vehicle 不能被实例化。它把 licence_category() 声明为抽象,所以每个具体子类都必须实现它,同时它仍提供 hire_summary() 作为所有车辆原样继承的可运行代码。”实例化、义务和共享代码都说到了。
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[2]Explain why licence_category() is declared abstract in Vehicle, while hire_summary() is not.
[2]解释为什么 licence_category() 在 Vehicle 中被声明为抽象,而 hire_summary() 不是。
Marking points
评分要点
- licence_category() has no answer that is correct for every vehicle: a car, a van and a minibus each need a different licence, so there is no sensible default and it is declared abstract to force each subclass to supply its own.
- hire_summary() does the same formatting work for every vehicle, so it can be written once as a concrete method in Vehicle and inherited unchanged.
- licence_category() 没有一个对每种车辆都正确的答案:轿车、厢式货车和小巴各需要不同的驾照,所以没有合理的默认值,把它声明为抽象以强制每个子类提供自己的实现。
- hire_summary() 对每种车辆做相同的格式化工作,所以它可以作为 Vehicle 中的一个具体方法写一次,并被原样继承。
[4]Lansdown adds minibuses at 80 per day, requiring a category D1 licence. Construct Minibus so that it satisfies the Vehicle contract.
[4]Lansdown 新增了小型巴士,每天 80,需要 D1 类驾照。构建 Minibus,使其满足 Vehicle 的契约。
Marking points
评分要点
- class Minibus(Vehicle): inheriting the shared attributes and hire_summary().
- Its constructor calls super().__init__(...) and sets the daily rate to 80.
- It implements the abstract method: def licence_category(self): return D1.
- Because it provides licence_category(), Minibus is now concrete and satisfies the Vehicle contract, so it can be instantiated and used anywhere a Vehicle is expected.
- class Minibus(Vehicle):,继承共享属性和 hire_summary()。
- 它的构造函数调用 super().__init__(...) 并把每日费率设为 80。
- 它实现抽象方法:def licence_category(self): return D1。
- 因为它提供了 licence_category(),Minibus 现在是具体的并满足 Vehicle 契约,所以它可以被实例化,并用在任何期望 Vehicle 的地方。
[3]A developer proposes replacing the abstract class with an ordinary parent class whose licence_category() returns "B". Evaluate this proposal for the hire firm.
[3]一位开发者建议用一个普通父类来替换这个抽象类,其 licence_category() 返回 "B"。针对这家租赁公司评价这个提议。
Marking points
评分要点
- An ordinary parent with licence_category() returning B removes the compiler or run-time check that every subclass provides its own.
- A new vehicle type that forgot to override it would silently inherit B, quoting the wrong licence, a serious error for a hire firm.
- The abstract class makes forgetting an error the developer must fix before the code runs.
- Evaluation: the proposal is a poor trade, swapping a guaranteed check for a hidden default; keep the abstract class.
- 一个返回 B 的普通父类 licence_category() 去掉了对每个子类提供自己实现的编译期或运行期检查。
- 一个忘记重写它的新车辆类型会悄悄继承 B,报出错误的驾照,对租赁公司来说是严重的错误。
- 抽象类使遗忘成为开发者在代码运行前必须修复的错误。
- 评价:该提案是一笔糟糕的交易,用一个隐藏的默认值换掉一个有保证的检查;保留抽象类。
Flashcards
闪卡
Active recall for this statement’s key terms.
针对本条陈述关键术语的主动回忆。
Keep this statement’s practice with you
把本条陈述的练习带在身边
Free account: unlock every revision question and flashcard for B3.2.3, and every other IB CS 2027 statement.
免费账号:解锁 B3.2.3 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。