B3.1.1 · Fundamentals of OOP for a single class
B3.1.1 · 单个类的 OOP 基础
The fundamentals of object-oriented programming
面向对象编程的基础
Five concepts, one recurring pattern: model the real world as things that hold their own data and know how to act on it.
五个概念,一个反复出现的模式:把现实世界建模为持有自己数据、并知道如何据此行动的事物。
Explainer
讲解
A smart-home app has to track a front-door lock, a thermostat, and a hallway light. All three are switched on or off. All three log a battery level. But locking a door and dimming a light are completely different actions. Writing one giant function full of if device_type == "lock" checks to handle every device would work, but it would grow unmanageable the moment a fourth device type showed up. Object-oriented programming (OOP) solves this by building each device as its own self-contained unit that knows how to behave.
一个智能家居应用要跟踪前门门锁、恒温器和走廊灯。这三者都能开或关,也都会记录电池电量。但锁门和调暗灯光完全是两种不同的动作。写一个巨大的函数,里面全是 if device_type == "lock" 这样的判断来处理每一种设备,倒也能用,但一旦出现第四种设备类型,它就会变得难以维护。面向对象编程(OOP)的解决办法,是把每个设备建成一个自成一体、知道如何行动的单元。
Object-oriented programming is a programming paradigm that models a system as a collection of interacting objects. Each object holds its own state, and the only code allowed to change that state lives inside the object itself, rather than in one long sequence of procedures all reaching into shared data.
面向对象编程是一种编程范式,它把系统建模为一组相互作用的对象。每个对象持有自己的状态,而唯一被允许改变这个状态的代码就在对象内部,而不是让一长串过程全都去伸手改共享的数据。
The whole paradigm rests on five ideas that keep showing up together: classes and objects (the blueprint and the real things built from it), inheritance (sharing a blueprint between related things), encapsulation (each thing guarding its own data), and polymorphism (related things responding to the same instruction in their own way).
整个范式建立在五个总是一起出现的思想上:类和对象(蓝图,以及依蓝图造出的真实事物)、继承(在相关事物之间共享一张蓝图)、封装(每个事物守护自己的数据),以及多态(相关的事物以各自的方式回应同一条指令)。
Worked example
例题讲解
Five concepts, one smart-home app
五个概念,一个智能家居应用
Every concept below is inspected through the same running scenario: a Device blueprint, and three real devices built from variations on it. Click through them in any order.
下面每个概念都放在同一个贯穿始终的场景里考察:一个 Device 蓝图,以及在它基础上变化出的三个真实设备。可以按任意顺序点开查看。
Class: the blueprint
类(Class):蓝图
A class defines what every device of that kind will have and be able to do, without describing any one real device yet. Nothing has been switched on or off until an actual object exists.
类规定了这一种设备都会具有什么、能做什么,而不去描述某一个具体设备。在真正的对象出现之前,什么都还没有被打开或关闭。
# the blueprint: no real device exists yet, just the shape every Light will have class Light: def __init__(self, device_id): self.device_id = device_id self.is_on = False self.brightness = 0 def toggle(self): self.is_on = not self.is_on
In this app: writing class Light: once defines every light the app will ever create, from one blueprint.
在这个应用里:只要写一次 class Light:,就定义了应用将来会创建的每一盏灯,都出自这同一张蓝图。
Object: one real thing built from the blueprint
对象(Object):依蓝图造出的一个真实事物
An object (an instance of the class) is one concrete device with its own state. Creating two objects from the same class gives two independent things, changing one never touches the other.
对象(类的一个实例)是一个带有自己状态的具体设备。用同一个类创建两个对象,得到的是两个互相独立的东西,改动其中一个绝不会影响另一个。
# two separate Light OBJECTS, each with its own independent state hallway_light = Light("L01") kitchen_light = Light("L02") hallway_light.toggle() # hallway_light.is_on becomes True # kitchen_light.is_on is still False, it is a completely separate object
In this app: hallway_light and kitchen_light share the same class, but toggling one never affects the other.
在这个应用里:hallway_light 和 kitchen_light 共用同一个类,但切换其中一盏绝不会影响另一盏。
Inheritance: sharing a blueprint between related things
继承(Inheritance):在相关事物之间共享一张蓝图
A lock, a thermostat, and a light are all still “devices”: each has a device_id, a battery level, and can be toggled. Rather than writing that shared behaviour three times, a general Device class defines it once, and Light, Thermostat, and Lock each inherit from it, adding only what makes them different.
锁、恒温器和灯仍然都是"设备":每个都有 device_id、电池电量,也都能被切换。与其把这些共同的行为写三遍,不如让一个通用的 Device 类只定义一次,Light、Thermostat 和 Lock 都从它继承,只添加各自与众不同的部分。
# Device holds what every device has in common class Device: def __init__(self, device_id): self.device_id = device_id self.is_on = False self.battery_level = 100 def toggle(self): self.is_on = not self.is_on # Light INHERITS device_id, is_on, battery_level and toggle() for free class Light(Device): def __init__(self, device_id): super().__init__(device_id) self.brightness = 0
In this app: Light(Device) means every light already has an ID, a battery level, and can toggle, none of that had to be rewritten.
在这个应用里:Light(Device) 意味着每盏灯已经拥有 ID、电池电量,也能切换,这些都不用重写。
Encapsulation: each device guards its own data
封装(Encapsulation):每个设备守护自己的数据
The battery level is stored inside the device itself, not as a value floating around the rest of the program. Reading or draining it happens through the device's own methods, so the device can enforce its own rule: it never reports a battery level below zero.
电池电量保存在设备内部,而不是作为一个在程序其余部分里飘来飘去的值。读取或消耗它,都通过设备自己的方法完成,所以设备可以执行自己的规则:它绝不会报告低于零的电量。
# battery_level is only ever touched through the device's own methods class Device: def __init__(self, device_id): self.device_id = device_id self.__battery_level = 100 # hidden def drain_battery(self, amount): self.__battery_level = max(0, self.__battery_level - amount) def get_battery_level(self): return self.__battery_level
In this app: no code outside Device can set __battery_level to a negative number, since nothing outside the class can touch it directly at all.
在这个应用里:Device 之外的任何代码都不能把 __battery_level 设成负数,因为类外的任何东西根本不能直接碰到它。
Polymorphism: the same instruction, a different response
多态(Polymorphism):同一条指令,不同的回应
Every device understands get_status(), but each kind of device answers it in its own way: a light reports brightness, a thermostat reports temperature, a lock reports whether it's locked. The caller sends the same message to any device without needing to know which kind it is.
每个设备都理解 get_status(),但每种设备以自己的方式回答它:灯报告亮度,恒温器报告温度,锁报告是否已上锁。调用者向任何设备发送同一条消息,而不需要知道它是哪一种。
# same method NAME, three different device-specific IMPLEMENTATIONS class Light(Device): def get_status(self): return f"brightness {self.brightness}%" class Thermostat(Device): def get_status(self): return f"set to {self.target_temp} deg" class Lock(Device): def get_status(self): return "locked" if self.is_locked else "unlocked"
In this app: calling device.get_status() works identically for any device, but which version actually runs depends on which kind of device it is.
在这个应用里:对任何设备调用 device.get_status() 的方式都一样,但实际运行的是哪个版本,取决于它是哪一种设备。
Worked example
例题讲解
Why this matters: all five together
为什么重要:五个概念合在一起
The real payoff shows up once several different device objects need to be handled the same way. This is the exact scenario from the explainer at the top of the page, solved properly.
当需要用同样的方式处理好几种不同的设备对象时,真正的好处才显现出来。这正是页面开头讲解里的那个场景,现在被妥善地解决了。
# one loop, three different device TYPES, zero if/elif chains devices = [Light("L01"), Thermostat("T01"), Lock("K01")] for device in devices: print(device.device_id, ":", device.get_status()) # adding a fourth device type later needs no change to this loop at all
Each object (instantiated from a class that inherits from Device) hides its own state (encapsulation) and responds to get_status() in its own way (polymorphism). The loop never has to ask “what kind of device is this,” it just trusts every object to know how to answer.
每个对象(由继承自 Device 的类实例化而来)隐藏自己的状态(封装),并以自己的方式回应 get_status()(多态)。循环永远不必问"这是什么类型的设备",它只需相信每个对象都知道如何回答。
Class defines the shape. Object is one real thing with that shape. Inheritance lets related shapes share what's common. Encapsulation keeps each object's data safe inside it. Polymorphism lets the same instruction get a different, correct answer from each kind of object.
类定义形状。对象是具有这种形状的一个真实事物。继承让相关的形状共享共同的部分。封装把每个对象的数据安全地留在它内部。多态让同一条指令从每一种对象那里得到各自正确的回答。
Try it yourself
动手试试
Edit the smart-home scenario and run it
编辑这个智能家居场景并运行
This is the same Device/Light/Thermostat/Lock code from above, live and editable. Try adding a fourth device class (a Fan, say) without touching the loop, that's the whole payoff of polymorphism made concrete.
这就是上面那套 Device/Light/Thermostat/Lock 代码,可以在线编辑运行。试着再加第四个设备类(比如 Fan),而不去动循环,这就是多态的全部好处,变得具体可见。
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 can still run this page's own scenario, classes, inheritance, self/super(), if/elif/else, loops over a list, but it isn't full Python.
正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它仍能运行本页自己的场景,包括类、继承、self/super()、if/elif/else、遍历列表的循环,但它不是完整的 Python。
Check your understanding
检查你的理解
In the smart-home example, which OOP concept lets a single loop call device.get_status() on a Light, a Thermostat, and a Lock, and get the correct kind of answer from each, without the loop ever checking the device's type?
在这个智能家居例子中,哪个 OOP 概念让同一个循环能对 Light、Thermostat 和 Lock 都调用 device.get_status(),并从每一个得到各自正确的回答,而循环完全不用检查设备的类型?
Common mistake
常见错误
B3.1.1B3.1.1 的这一常见模式RecurringCandidates frequently swap the words class and object, describing a class as “a single device” or an object as “the blueprint,” which loses marks even when the surrounding explanation shows real understanding of the mechanism.
反复出现考生经常把类和对象这两个词互换,把类说成"某一个设备",或把对象说成"蓝图",即使其余解释显示出对机制的真正理解,这样也会丢分。
Answer frame that scores: name the class as the definition/template → name the object as one specific instance created from it → give a concrete example of each from the scenario in the question.
能得分的答题框架:指出类是定义/模板 → 指出对象是由它创建的一个具体实例 → 从题目的场景中各举一个具体例子。
What a weak answer looks like: “Light is an object that stores the brightness of the hallway light.” This calls the class an object, and describes ONE specific light as if it were the general definition.
较弱的答案是这样的:“Light 是一个对象,保存走廊灯的亮度。”这把类称作了对象,并且把某一盏具体的灯当成了通用的定义来描述。
What it should say: “Light is the class: it defines that every light has a brightness and can be toggled. hallway_light is an object, one specific instance of Light, with its own actual brightness value.” Class and object are named correctly and tied to a concrete example.
应该这样写:“Light 是类:它规定每盏灯都有亮度并且可以切换。hallway_light 是对象,是 Light 的一个具体实例,有它自己实际的亮度值。”类和对象的称呼正确,并且与一个具体例子联系了起来。
Explainer
讲解
Advantages and disadvantages of choosing OOP
选择 OOP 的优点与缺点
“Evaluate” questions on this statement expect a real trade-off, not a one-sided list, and B3's own guiding question asks exactly this: is OOP the right paradigm here, or would a simpler approach do?
这条陈述上的"Evaluate(评价)"类题目期望给出真正的权衡,而不是片面的清单,B3 自己的引导性问题问的正是这个:这里 OOP 是合适的范式,还是更简单的做法就够了?
Real example: one handle_device(device_type, state) function with an if/elif chain for every device type.
实际例子:一个 handle_device(device_type, state) 函数,里面为每种设备类型写一条 if/elif 链。
Advantage
优点
- Fast to write for a small, fixed set of cases (no classes, no inheritance hierarchy to design first)
- 对小而固定的情形写起来很快 (没有类,也不必先设计继承层次)
Disadvantage
缺点
- Every new device type means editing the same shared function (a fourth device type forces a change to code that already works for the first three, risking a new bug in previously-tested logic)
- 每增加一种新设备类型,就要修改同一个共享函数 (第四种设备类型迫使你改动对前三种本来已经正常的代码,有给早已测试过的逻辑引入新错误的风险)
Real example: the Device/Light/Thermostat/Lock hierarchy above, called through one polymorphic loop.
实际例子:上面的 Device/Light/Thermostat/Lock 层次结构,通过一个多态循环来调用。
Advantage
优点
- A new device type is a new class, added without touching existing ones (the loop that calls get_status() never changes, so working code for Light and Thermostat can't be broken by adding Lock)
- 新的设备类型就是一个新类,添加时不用改动已有的类 (调用 get_status() 的循环永远不变,所以加入 Lock 不会破坏 Light 和 Thermostat 已经能用的代码)
Disadvantage
缺点
- More design effort upfront (deciding what belongs in the shared Device class versus each subclass takes real planning before any device-specific code is written)
- 前期设计工作更多 (要决定哪些属于共享的 Device 类、哪些属于各个子类,在写任何设备专属代码之前,都需要认真规划)
The trade-off is scale versus overhead: OOP earns its cost back once a system has multiple related, evolving entity types, which is exactly the kind of complex, growing problem B3's guiding question is asking about. A one-off script with a single fixed behaviour rarely needs it.
这个权衡是规模与开销之间的:当系统里有多个相关且不断演变的实体类型时,OOP 就能把它的成本赚回来,这正是 B3 的引导性问题所指的那种复杂且不断增长的问题。只有单一固定行为的一次性脚本,很少需要它。
Linking question
联系性问题
How this connects to the rest of the syllabus
这与考纲其余部分如何联系
The IB syllabus is deliberately woven together, not a stack of isolated topics. Here's how OOP connects specifically to B2 (data structures and algorithms).
IB 考纲是刻意编织在一起的,而不是一堆孤立的主题。下面是 OOP 与 B2(数据结构与算法)的具体联系。
Is OOP necessary for all programming, or only in modelling complex situations? (The smart-home example above shows the actual trade-off directly: a single fixed algorithm rarely benefits from classes at all, but a system of several related, evolving entity types is exactly where the extra design effort pays off.)
OOP 对所有编程都是必需的,还是只在对复杂情形建模时才需要?(上面的智能家居例子直接展示了真实的权衡:单一固定的算法几乎用不上类,而由多个相关且不断演变的实体类型构成的系统,正是额外设计工作能够物有所值的地方。)
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[2]Distinguish between a class and an object, using the Light class as an example.
[2]以 Light 类为例,区分类和对象。
Marking points
评分要点
- A class is a blueprint: Light defines the attributes (device_id, is_on, brightness) and methods (toggle) that every light will have.
- An object is a specific instance built from that blueprint, for example one particular Light with its own device_id and its own on/off state.
- 类是一个蓝图:Light 定义了每盏灯将拥有的属性(device_id、is_on、brightness)和方法(toggle)。
- 对象是从该蓝图构建的一个具体实例,例如某一盏特定的 Light,有它自己的 device_id 和自己的开关状态。
[3]Outline how inheritance reduces duplicated code across the Light, Thermostat, and Lock classes.
[3]概述继承如何减少 Light、Thermostat 和 Lock 这几个类之间的重复代码。
Marking points
评分要点
- Light, Thermostat and Lock share behaviour such as an identifier, a connected state and a way to report status.
- Putting that common code in a shared parent class (for example Device) means it is written once, not three times.
- Each of Light, Thermostat and Lock then inherits it and adds only what is specific to that device.
- A change or fix to the shared behaviour is made once in the parent and applies to all three.
- Light、Thermostat 和 Lock 共享一些行为,如一个标识符、一个连接状态和一种报告状态的方式。
- 把这些公共代码放在一个共享的父类中(例如 Device),意味着它只写一次,而不是三次。
- 然后 Light、Thermostat 和 Lock 各自继承它,只添加该设备特有的部分。
- 对共享行为的改动或修复在父类中做一次,即应用到三者。
[4]Evaluate whether an object-oriented approach is appropriate for a program that only ever needs to reverse a single list of numbers.
[4]评价:对于一个只需要反转一个数字列表的程序,面向对象的做法是否合适。
Marking points
评分要点
- Reversing a single list has no state to model, no variety of related things, and no behaviour to attach to data.
- An OOP approach would add a class, a constructor and method syntax with no reuse or clarity benefit.
- A single function (or one line) is simpler, shorter and easier to test.
- Conclusion: OOP is not appropriate here; it is suited to programs with multiple interacting entities that have state and behaviour.
- 反转一个列表没有状态需要建模,没有相关事物的多样性,也没有需要附着到数据上的行为。
- 面向对象的做法会增加一个类、一个构造函数和方法语法,却没有复用或清晰度上的好处。
- 单个函数(或一行代码)更简单、更短、更易测试。
- 结论:这里不适合面向对象;它适合有多个相互作用、具备状态和行为的实体的程序。
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.1.1, and every other IB CS 2027 statement.
免费账号:解锁 B3.1.1 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。