B3.1.5 · Fundamentals of OOP for a single class
B3.1.5 · 单个类的 OOP 基础
Encapsulation & information hiding
封装与信息隐藏
Why a class hides its own data, and how the methods around it are the only door in.
为什么类要隐藏自己的数据,以及围绕数据的方法为什么是唯一的入口。
Explainer
讲解
Think of a car’s dashboard. You press the accelerator and the brake; you never reach under the bonnet and spin the engine by hand. The dashboard is the only door in, and everything behind it is off limits. That’s exactly what encapsulation gives a class.
想想汽车的仪表盘。你踩油门和刹车,但从不会钻到引擎盖下面用手去拨动发动机。仪表盘是唯一的入口,后面的一切都不允许直接碰。这正是封装带给一个类的东西。
Encapsulation is the practice of hiding an object’s internal implementation details and exposing only what the rest of the program needs, through a defined set of methods.
封装(Encapsulation)是指隐藏对象内部的实现细节,只通过一组规定好的方法,向程序其余部分公开它所需要的部分。
A class does this by marking its attributes private and giving the outside world public methods to read or change them, never direct access to the variable itself. That’s information hiding: the data is still there, it’s just not reachable except through the door the class chose to leave open.
类的做法是把属性标记为 private(私有),并提供 public(公有)方法来读取或修改它们,而不允许直接访问变量本身。这就是信息隐藏:数据依然在那里,只是除了类特意留出的那扇门,别处都够不着。
The two ideas are often tested together but they answer different questions. Information hiding is what is hidden (the attributes). Encapsulation is the whole mechanism: bundling the data with the methods that are allowed to touch it, so the class itself can guarantee its own rules are never broken.
这两个概念常常一起考,但回答的是不同的问题。信息隐藏说的是隐藏了什么(属性)。封装说的是整个机制:把数据和允许触碰它的方法捆绑在一起,这样类本身就能保证自己的规则不被破坏。
Python does not actually enforce any of this. Java has four real access modifiers, checked by the compiler: private (this object only), protected (this object and anything that inherits it, covered properly once inheritance is taught), public (anywhere), and a fourth, unnamed default level when no keyword is written at all (accessible anywhere in the same package). Python has no keywords and no equivalent to that default package-level modifier, only a naming convention with three levels instead: no underscore is public (the default), a single leading underscore (_spaces_free) signals "internal use only" but is purely a hint, nothing stops outside code reaching it, and a double leading underscore (self.__spaces_free, used below) triggers name mangling: Python renames it internally to _CarPark__spaces_free, so a stray typo or an accidental reference can no longer stumble onto it, though anyone who deliberately goes looking for _CarPark__spaces_free by name can still find it. Same idea, very different level of enforcement, and IB expects you to know which is which.
Python 其实并不强制执行这些。Java 有四种由编译器检查的真正的访问修饰符:private(仅本对象),protected(本对象及其继承者,讲到继承时再细说),public(任何地方),以及第四种不写任何关键字时的无名默认级别(同一个包内任何地方都可访问)。Python 没有这些关键字,也没有对应默认包级别的修饰符,只有一套分三级的命名约定:不带下划线就是公有(默认);一个前导下划线(_spaces_free)表示"仅供内部使用",但这纯粹是提示,没有任何东西能阻止外部代码访问它;两个前导下划线(self.__spaces_free,下面会用到)会触发名称改写(name mangling):Python 在内部把它改名为 _CarPark__spaces_free,于是一次手误或意外的引用就不会再碰到它,不过如果有人故意按名字去找 _CarPark__spaces_free,仍然能找到。思路相同,强制程度却大不一样,IB 期望你能分清二者。
Accessor and mutator (also called getter and setter) are the formal names for the public methods that do the reading and writing a private attribute can no longer do directly. An accessor returns a private value without changing it (getSpacesFree() below). A mutator changes one, but unlike a plain "setter" that just overwrites a value, vehicleEntered() below is a mutator that VALIDATES first, this is exactly what separates real encapsulation from simply hiding a variable: the mutator is where the class's own rules actually get enforced.
访问器(accessor)和修改器(mutator)(也叫 getter 和 setter)是公有方法的正式名称,它们负责完成私有属性不能再被直接读写的那些操作。访问器返回私有值而不改变它(下面的 getSpacesFree())。修改器会改变它,但与只会直接覆盖数值的普通 "setter" 不同,下面的 vehicleEntered() 是一个会先验证的修改器,这正是真正的封装与仅仅隐藏一个变量的区别:类自己的规则,就是在修改器里真正被执行的。
Worked example
例题讲解
A CarPark that protects its own space count
一个保护自己空位数量的 CarPark
Holloway Lane Car Park has 40 bays. The number of free spaces must never fall below zero, and must never climb above the capacity of the site either. If that count were public, any line of code anywhere in the program could set it to whatever it wanted, and both rules would depend on every programmer remembering to check them. Encapsulation moves that responsibility inside the class itself.
Holloway Lane 停车场有 40 个车位。空位数量绝不能低于零,也绝不能超过场地的总容量。如果这个数是公开的,程序里任何地方的任何一行代码都可以随意设置它,这两条规则就都得靠每一位程序员记得去检查。封装把这份责任移到了类的内部。
Click an attribute or method to see which ones connect.
点击一个属性或方法,查看哪些成员与它相连。
# spaces_free is PRIVATE: outside code cannot write park.spaces_free directly (leading __) class CarPark: def __init__(self, site_name, capacity): self.site_name = site_name self.__capacity = capacity self.__spaces_free = capacity def get_spaces_free(self): return self.__spaces_free def vehicle_entered(self): if self.__spaces_free > 0: self.__spaces_free -= 1 return True return False # rule enforced HERE, once, not everywhere spaces_free is used
// spacesFree is PRIVATE: outside code cannot write park.spacesFree directly public class CarPark { private int spacesFree; private int capacity; public int getSpacesFree() { return spacesFree; } public boolean vehicleEntered() { if (spacesFree > 0) { spacesFree--; return true; } return false; // rule enforced HERE, once, not everywhere spacesFree is used } }
getSpacesFree() is the accessor, it only reads. vehicleEntered() is the mutator, and every path that changes spacesFree runs through it. That single choke point is what makes the “never below zero” rule actually reliable.
getSpacesFree() 是访问器,它只读取。vehicleEntered() 是修改器,所有改变 spacesFree 的路径都必须经过它。正是这个唯一的关卡,让"不会低于零"这条规则真正可靠。
What is self.__spaces_free (Python), or plain spacesFree inside a Java method? It’s not one shared number. It’s the free-space count belonging to this particular car park. Create two sites, north = CarPark("North", 40) and south = CarPark("South", 120), and each gets its own private copy: filling north never touches south’s count.
self.__spaces_free(Python),或 Java 方法里的 spacesFree,到底是什么?它不是一个大家共用的数。它是属于这一个停车场的空位数量。创建两个场地,north = CarPark("North", 40) 和 south = CarPark("South", 120),各自拥有一份私有的副本:让 north 停满车,完全不会影响 south 的数量。
What does north.reserve(12) actually do? It refers to north’s own free-space count, reduced by 12. Which object (north) stays fixed for the whole call; the count (12) is the part that changes each time you call it. Inside the method, that fixed object is exactly what self.__spaces_free (or spacesFree in Java) refers to, never any other site’s.
north.reserve(12) 实际上做了什么?它指向的是north 自己的空位数量,并减去 12。整个调用过程中,对象(north)保持不变;数量(12)才是每次调用都会变的部分。在方法内部,那个不变的对象正是 self.__spaces_free(Java 中是 spacesFree)所指的对象,绝不会是其他场地的。
Making spacesFree private is information hiding on its own. It only becomes encapsulation once vehicleEntered() and reserve() exist as the sole route in, so the data and the rule that protects it are bundled into one unit.
把 spacesFree 设为私有,本身只是信息隐藏。只有当 vehicleEntered() 和 reserve() 作为唯一的进入通道存在时,它才成为封装,因为这时数据以及保护它的规则被捆绑成了一个整体。
Try it yourself
动手试试
Watch encapsulation actually refuse you
看看封装如何真的拒绝你
The CarPark class from above, live and editable. The last line is commented out on purpose: uncomment it and press Run to see Python genuinely block direct access to a private attribute, rather than just discouraging it by convention.
上面的 CarPark 类,可在线编辑运行。最后一行故意被注释掉了:取消注释并点击运行,你会看到 Python 真正地拦下对私有属性的直接访问,而不只是靠约定来劝阻。
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 private attributes and name mangling, but it isn't full Python: one visible difference is that a whole-number float prints without its trailing .0.
正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括私有属性和名称改写,但它不是完整的 Python:一个明显的差别是,整数值的浮点数打印时不带末尾的 .0。
Try north.reserve(100) on a site with 28 spaces left and watch the mutator refuse it. Try north.site_name = "Somewhere else" and see that a public attribute has no such protection. Then try reaching the private count the way the explainer described, as north._CarPark__spaces_free, and notice it works: Python hides the attribute from accidents, not from someone deliberately going around the interface.
在只剩 28 个空位的场地上试 north.reserve(100),看修改器如何拒绝它。再试 north.site_name = "Somewhere else",你会看到公有属性没有这样的保护。然后试试用讲解里说的方式去访问私有数量,即 north._CarPark__spaces_free,你会发现它能成功:Python 是让属性避开意外访问,而不是防住有意绕过接口的人。
Check your understanding
检查你的理解
Why does CarPark make spacesFree private instead of public?
为什么 CarPark 把 spacesFree 设为私有,而不是公有?
Common mistake
常见错误
B3.1.5B3.1.5 的这一常见模式RecurringCandidates who clearly know the word encapsulation still lose marks for an incomplete definition. The mark scheme wants the full idea: hiding internal detail and exposing only what’s necessary, not just a one-line mention that variables are private.
反复出现很清楚封装这个词的考生,仍会因为定义不完整而丢分。评分标准要的是完整的意思:隐藏内部细节,并且只公开必要的部分,而不只是一句"变量是私有的"。
On code-based questions asking how encapsulation has been used in a given program, the weaker answers restate that the class has private variables without saying which method controls them or why. That’s a description too generic to earn full marks.
在要求说明封装如何应用于某段程序的代码题中,较弱的答案只是重复说这个类有私有变量,却不说是哪个方法在控制它们,也不说为什么。这样的描述太笼统,拿不到满分。
Answer frame that scores: name the private attribute → name the specific accessor/mutator that touches it → state the rule that method enforces.
能得分的答题框架:指出私有属性 → 指出访问它的具体访问器/修改器 → 说明该方法执行的规则。
What a weak answer looks like: “spacesFree is private, which makes the class more secure.” True, but it names nothing specific: no attribute-to-method link, no rule being enforced. This is the “generic response” pattern markers reported losing marks.
较弱的答案是这样的:“spacesFree 是私有的,这让类更安全。”这话没错,但没有指出任何具体内容:没有属性与方法的联系,也没有被执行的规则。这正是阅卷员反馈的会丢分的"笼统回答"模式。
What it should say: “spacesFree is private, so only getSpacesFree(), vehicleEntered() and reserve() can access it. vehicleEntered() checks spacesFree > 0 before subtracting, so it can guarantee the count never drops below zero, a guarantee that would be impossible if spacesFree were public.” Attribute named, method named, rule stated.
应该这样写:“spacesFree 是私有的,所以只有 getSpacesFree()、vehicleEntered() 和 reserve() 可以访问它。vehicleEntered() 在减法之前先检查 spacesFree > 0,因此能保证数量永远不会降到零以下;如果 spacesFree 是公有的,这个保证就不可能做到。”点出了属性,点出了方法,说明了规则。
Explainer
讲解
The advantage examiners actually want stated
考官真正想看到的那个优点
“Outline one advantage of encapsulation” questions are answered well most often, but only when the advantage is tied to a consequence, not left abstract.
“Outline one advantage of encapsulation(概述封装的一个优点)”这类题通常得分不错,但前提是把优点与一个结果联系起来,而不是停留在抽象层面。
Real example: a multi-site parking app where dozens of files across the codebase all touch park.spacesFree directly.
实际例子:一个多场地停车应用,代码库里几十个文件都直接操作 park.spacesFree。
Advantage
优点
- Simple to write (no method call needed, just read or overwrite the variable directly)
- 写起来简单 (不需要调用方法,直接读取或覆盖变量就行)
Disadvantage
缺点
- No shared rule can be guaranteed (any one of those dozens of files could push spacesFree below zero or above capacity by mistake, and there is no single place to catch it)
- 无法保证有统一的规则 (这几十个文件中任何一个都可能因失误把 spacesFree 推到零以下或超过容量,而且没有一个统一的地方能拦住它)
Real example: the same app, but every file calls park.vehicleEntered() instead of touching spacesFree directly.
实际例子:还是同一个应用,但每个文件都调用 park.vehicleEntered(),而不是直接操作 spacesFree。
Advantage
优点
- The rule is enforced in exactly one place (it prevents any part of the program from putting the object into an invalid state, because every change has to go through a method that checks it first)
- 规则只在一个地方执行 (它能防止程序的任何部分让对象进入无效状态,因为每次改动都必须先经过一个会检查的方法)
Disadvantage
缺点
- More code to write upfront (every attribute that needs outside access needs its own accessor and/or mutator method, not just a bare variable)
- 前期要多写代码 (每个需要被外部访问的属性,都要有自己的访问器和/或修改器方法,而不只是一个裸变量)
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 encapsulation connects specifically to A3 (networks), worth thinking through, not just memorising: it's the kind of synthesis a Paper 1/2 question can genuinely ask for.
IB 考纲是刻意编织在一起的,而不是一堆孤立的主题。下面是封装与 A3(网络)的具体联系,值得认真想一想,而不是死记:这正是试卷 1/2 的题目真正可能要求的综合。
How can the principles of encapsulation and information hiding be applied to secure network communication? (The same idea, hide the internal state, expose only a controlled interface, is exactly how a secure network service works: nothing outside it can reach its internal data directly, only through the specific requests it chooses to accept.)
封装和信息隐藏的原则如何应用于保护网络通信?(同样的思路,隐藏内部状态,只公开一个受控的接口,正是安全的网络服务的工作方式:外部的任何东西都不能直接触及它的内部数据,只能通过它选择接受的特定请求。)
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[1]Define the term encapsulation.
[1]定义术语封装(encapsulation)。
Marking points
评分要点
- Encapsulation is bundling an object's data together with the methods that operate on it, and controlling access to that data from outside the class.
- 封装是把对象的数据与作用于它的方法捆绑在一起,并控制类外部对该数据的访问。
[2]Outline one consequence of declaring the attribute spacesFree as private in the class above.
[2]概述在上面的类中把属性 spacesFree 声明为 private 所带来的一个结果。
Marking points
评分要点
- Making spacesFree private means outside code cannot read or change it directly.
- Any change must go through a method of the class, so the class can keep spacesFree correct (for example never negative, never above capacity).
- 把 spacesFree 设为私有意味着外部代码不能直接读取或更改它。
- 任何改动都必须通过类的一个方法进行,所以类可以保持 spacesFree 正确(例如永不为负,永不超过容量)。
[3]A junior developer suggests removing vehicleEntered() and making spacesFree public instead, to “simplify the code.” Explain why this is a poor design decision.
[3]一位初级开发者建议删除 vehicleEntered(),并把 spacesFree 改为公有,以"简化代码"。解释为什么这是一个糟糕的设计决定。
Marking points
评分要点
- If spacesFree were public, any code anywhere could set it to any value, including invalid ones, so the count could no longer be trusted.
- vehicleEntered() is the controlled way to change the count: it can apply rules and keep related data consistent.
- Removing it also breaks encapsulation, coupling every caller to the internal representation, so a later change to how spaces are tracked would break all of them.
- The small saving in code is not worth losing that safety and flexibility.
- 如果 spacesFree 是公有的,任何地方的任何代码都可以把它设为任意值,包括无效值,于是这个计数不再可信。
- vehicleEntered() 是更改计数的受控方式:它可以应用规则并保持相关数据一致。
- 移除它还破坏封装,把每个调用者与内部表示耦合,于是之后改变车位跟踪方式会破坏所有这些调用者。
- 代码上的小小节省不值得失去那份安全性和灵活性。
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.5, and every other IB CS 2027 statement.
免费账号:解锁 B3.1.5 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。