First exams 2027 · SL & HL2027 年首次开考 · SL 与 HL

B3.1.4 · Fundamentals of OOP for a single class

B3.1.4 · 单个类的 OOP 基础

Defining classes and instantiating objects

定义类并实例化对象

Writing the blueprint, then bringing real objects into existence from it, with every attribute set correctly from the very first moment.

先写好蓝图,再依它创造真实的对象,并且从最初的那一刻起,每个属性就都设置正确。

Core for SL & HL Typically 3–6 marks · AO2/AO3 Command term: construct
SL 与 HL 核心内容 通常 3–6 分 · AO2/AO3 指令词:construct

Explainer

讲解

Brackenhill Aquarium runs twelve display tanks. When a new tank is brought online, it is never registered half-configured: its reference code, its volume, and its target temperature are all recorded at the moment it enters the system. A tank sitting in the database with no temperature is not merely untidy, it is a tank nobody knows how to heat. Code has exactly the same requirement, and the constructor is what enforces it.

Brackenhill 水族馆运营着十二个展示水箱。一个新水箱上线时,绝不会以配置了一半的状态登记:它的编号、容积和目标温度,在它进入系统的那一刻就全部记录下来。数据库里有一个没有温度的水箱,不只是不整洁,而是一个没人知道该怎么加热的水箱。代码有完全相同的要求,而构造方法就是用来保证这一点的。

Df

Defining a class means writing the blueprint: the attributes every object of that kind will hold, and the methods it will be able to perform. Defining a class creates no objects and reserves no data, it only describes what objects will look like.

定义类是指写出蓝图:这一类对象都会持有的属性,以及它们能够执行的方法。定义一个类并不会创建任何对象,也不会保留任何数据,它只是描述对象将会是什么样子。

Df

Instantiation is creating a real object from that blueprint. Each instantiation produces a separate object in memory with its own attribute values, and returns a reference to it that can be stored in a variable.

实例化是依照那张蓝图创建一个真实的对象。每次实例化都会在内存中产生一个独立的对象,带有它自己的属性值,并返回对它的一个引用,可以存放在变量里。

# DEFINING the class: a blueprint, no tanks exist yet
class Tank:
    def __init__(self, ref, litres, target_temp):
        self.ref = ref
        self.litres = litres
        self.target_temp = target_temp
        self.is_heated = False

    def describe(self):
        return f"{self.ref}: {self.litres}L at {self.target_temp}C"


# INSTANTIATING: two real, separate tank objects
reef = Tank("BR-01", 200, 25.0)
coldwater = Tank("BR-02", 450, 14.0)
// DEFINING the class: a blueprint, no tanks exist yet
public class Tank {
    private String ref;
    private int litres;
    private double targetTemp;
    private boolean isHeated;

    // the constructor: same name as the class, no return type
    public Tank(String ref, int litres, double targetTemp) {
        this.ref = ref;
        this.litres = litres;
        this.targetTemp = targetTemp;
        this.isHeated = false;
    }
}

// INSTANTIATING: two real, separate tank objects
Tank reef = new Tank("BR-01", 200, 25.0);
Tank coldwater = new Tank("BR-02", 450, 14.0);

Both languages do the same two jobs, with different spellings. Python names the constructor __init__ and takes self explicitly; Java names it after the class, declares no return type, and uses this. Java also needs new to instantiate, where Python just calls the class.

两种语言做的是同样的两件事,只是写法不同。Python 把构造方法命名为 __init__,并显式地接收 self;Java 用类名来命名它,不声明返回类型,并使用 this。Java 还需要 new 来实例化,而 Python 只需直接调用类。

Explainer

讲解

What the constructor is actually for

构造方法究竟是干什么的

Df

A constructor is the special method that runs automatically the moment an object is created. Its job is to initialize the object's state: giving every attribute a starting value so the object is valid and usable from the instant it exists.

构造方法(constructor)是一种特殊的方法,在对象创建的那一刻自动运行。它的任务是初始化对象的状态:给每个属性一个起始值,使对象从存在的那一瞬间起就是有效且可用的。

Notice the two different sources those starting values come from, because questions often ask for both:

请注意这些起始值的两个不同来源,因为题目常常两者都会问:

1

Values passed in by whoever creates the object. ref, litres, and target_temp differ for every tank, so they arrive as parameters. The constructor's job is to store them on the object.

由创建对象的一方传入的值。ref、litres 和 target_temp 每个水箱都不同,所以它们作为参数传入。构造方法的任务是把它们存到对象上。

2

Values the class decides for itself. is_heated starts as False for every new tank, no matter who creates it, because a tank that has just been registered has not been switched on yet. Nobody passes this in; the constructor sets it.

由类自己决定的值。is_heated 对每个新水箱起始都是 False,无论是谁创建的,因为刚登记的水箱还没有被打开。没有人传入它;这是构造方法设置的。

Why this earns marks为什么这能得分

A constructor does not just "create the object." Creation happens anyway. What the constructor adds is a guarantee: there is no moment at which a Tank exists with a missing reference or an unknown temperature, because the object is not handed back until every attribute has been set.

构造方法不只是"创建对象"。创建本来就会发生。构造方法额外提供的是一个保证:不存在这样的时刻,即一个 Tank 已经存在,却缺少编号或温度未知,因为在每个属性都设置好之前,对象不会被交还。

Explainer

讲解

Anatomy of self.ref = ref

self.ref = ref 的结构

This single line confuses more students than any other part of the statement, because the same word appears twice meaning two different things.

这一行让学生困惑的程度超过这条陈述的任何其他部分,因为同一个词出现了两次,却表示两个不同的东西。

self.ref = ref
  • self.refThe attribute: permanent storage belonging to this object. It survives after the constructor finishes and can be read later as reef.ref.
  • self.ref这个属性:属于这个对象的永久存储。构造方法结束后它依然存在,以后可以用 reef.ref 读取。
  • refThe parameter: a temporary variable holding the value that was passed in. It disappears the moment the constructor finishes.
  • ref这个参数:一个临时变量,保存传入的值。构造方法一结束它就消失。
  • =Copies the parameter's value into the attribute. Without this line the value arrives, is never stored, and is silently lost.
  • =把参数的值复制到属性中。没有这一行,值虽然传进来了,却从未被存储,悄无声息地丢失了。

They are conventionally given the same name because they hold the same thing, but they are not the same variable. Writing ref = ref instead just reassigns the parameter to itself, and the object ends up with no ref attribute at all.

按惯例它们取同一个名字,因为它们保存的是同一个东西,但它们并不是同一个变量。如果写成 ref = ref,只是把参数重新赋值给它自己,对象最终根本没有 ref 属性。

Worked example

例题讲解

What actually happens when you write Tank("BR-01", 200, 25.0)

写下 Tank("BR-01", 200, 25.0) 时究竟发生了什么

Object creation looks like one instruction, but it is four distinct events. Step through them to see exactly when the object becomes usable.

创建对象看起来像一条指令,其实是四个不同的事件。一步一步看,就能准确知道对象是在什么时候变得可用的。

Creating the reef tank Step 1 of 5
创建礁石水箱 第 1 步,共 5 步

Step 1. The call is made. The three arguments are evaluated. No object exists yet, and the variable reef has nothing in it.

第 1 步。发出调用。三个参数被求值。此时还没有对象存在,变量 reef 里什么也没有。

reef = Tank("BR-01", 200, 25.0)
No object yet
还没有对象

Step 2. An empty object is created. Memory is set aside for one Tank, but none of its attributes have values. This half-built state is exactly what the constructor exists to eliminate, and it is why the object is not handed back yet.

第 2 步。创建一个空对象。内存为一个 Tank 预留了位置,但它的所有属性都还没有值。这种半成品状态正是构造方法要消除的,也是对象此时还不被交还的原因。

a new, empty Tank object is allocated
分配了一个全新的、空的 Tank 对象
new Tank object
新的 Tank 对象
ref = not set
ref = 未设置
litres = not set
litres = 未设置
target_temp = not set
target_temp = 未设置
is_heated = not set
is_heated = 未设置

Step 3. The constructor runs, with the new object as self. The parameters are bound to the values that were passed in, and each assignment copies one into the object.

第 3 步。构造方法运行,新对象作为 self。参数被绑定到传入的值,每一次赋值都把其中一个复制到对象里。

def __init__(self, ref, litres, target_temp): self.ref = ref self.litres = litres self.target_temp = target_temp
the object, mid-construction
构造过程中的对象
ref = "BR-01"
litres = 200
target_temp = 25.0
is_heated = not set
is_heated = 未设置

Step 4. The class sets its own default. Nobody passed is_heated in. The constructor decides it, because every newly registered tank starts switched off. The object is now complete.

第 4 步。类设置自己的默认值。没有人传入 is_heated。构造方法自己决定它,因为每个新登记的水箱起始都是关闭状态。对象现在完整了。

self.is_heated = False
the object, now valid
现在有效的对象
ref = "BR-01"
litres = 200
target_temp = 25.0
is_heated = False

Step 5. A reference to the finished object is returned and stored. Only now does reef point at anything. Creating a second tank repeats all four events and produces a completely separate object.

第 5 步。完成的对象的引用被返回并存储。直到此刻,reef 才指向了某个东西。创建第二个水箱会把这四个事件重复一遍,产生一个完全独立的对象。

reef = the finished object above coldwater = Tank("BR-02", 450, 14.0) # a second, separate object
reef
ref = "BR-01"
litres = 200
target_temp = 25.0
is_heated = False
coldwater
ref = "BR-02"
litres = 450
target_temp = 14.0
is_heated = False

Explainer

讲解

Default values in the constructor

构造方法中的默认值

Step 4 showed the class fixing a value nobody can override. There is a middle option too: a parameter with a default, which the caller may supply but does not have to.

第 4 步展示了类固定某个无人能覆盖的值。还有一个折中的做法:带默认值的参数,调用者可以提供,但不是必须提供。

# target_temp has a default; ref and litres do not
class Tank:
    def __init__(self, ref, litres, target_temp=24.0):
        self.ref = ref
        self.litres = litres
        self.target_temp = target_temp


tropical = Tank("BR-03", 180)          # target_temp becomes 24.0
coldwater = Tank("BR-04", 450, 14.0)   # target_temp becomes 14.0

Most Brackenhill tanks are tropical, so 24.0 is the sensible default and only the unusual tanks state a temperature. Parameters with defaults must come after those without, since Python matches arguments by position.

Brackenhill 的大多数水箱是热带水箱,所以 24.0 是合理的默认值,只有特殊的水箱才需要说明温度。带默认值的参数必须放在没有默认值的参数之后,因为 Python 按位置匹配参数。

Three ways an attribute gets its starting value属性获得起始值的三种方式

Required parameter (the caller must give it), parameter with a default (the caller may give it), or fixed inside the constructor (the caller cannot give it at all). Choosing correctly between the three is the design judgment this statement is really testing.

必需参数(调用者必须给出)、带默认值的参数(调用者可以给出),或在构造方法内固定(调用者根本无法给出)。在这三者之间正确地选择,正是这条陈述真正考查的设计判断。

Try it yourself

动手试试

Build your own tanks

建造你自己的水箱

The Brackenhill class, live and editable. Two things worth trying: delete the self.litres = litres line and see the error that appears only later, when something asks for it, and create a tank without its arguments to see what the constructor demands.

Brackenhill 的类,可在线编辑运行。有两件值得尝试的事:删掉 self.litres = litres 这一行,看看那个直到以后有东西需要它时才出现的错误;再创建一个不带参数的水箱,看构造方法要求什么。

main.py
Loading Python engine…
Output
输出
Press Run to see the output here.

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 constructors and default parameter values, but it isn't full Python: one visible difference is that whole-number floats print as 25 here rather than Python's 25.0.

正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括构造方法和默认参数值,但它不是完整的 Python:一个明显的差别是,整数值的浮点数在这里打印为 25,而不是 Python 的 25.0。

Check your understanding

检查你的理解

A student writes a constructor whose body is ref = ref instead of self.ref = ref. The program creates a Tank successfully, then crashes later when it calls reef.describe(). Why?

一位学生写的构造方法,函数体是 ref = ref 而不是 self.ref = ref。程序成功创建了一个 Tank,随后在调用 reef.describe() 时崩溃。为什么?

Common mistake

常见错误

Markers reported this pattern for B3.1.4
阅卷员反馈了 B3.1.4 的这一常见模式

RecurringOn "construct a class" questions, the most common lost mark is a constructor that takes parameters but never assigns them to attributes, writing ref = ref rather than self.ref = ref. The code looks complete and creates an object without error, so candidates rarely spot it.

反复出现在"构造一个类"的题目中,最常丢的分是:构造方法接收了参数,却从未把它们赋给属性,写成 ref = ref 而不是 self.ref = ref。代码看起来完整,创建对象时也不报错,所以考生很少察觉。

On written questions, describing the constructor's role as "it creates the object" is treated as too vague. The creditworthy point is that it initializes the object's attributes, giving the object a valid starting state.

在文字题中,把构造方法的作用描述成"它创建对象"会被认为过于含糊。能得分的要点是它初始化对象的属性,让对象具有一个有效的起始状态。

Answer frame that scores: say when it runs (automatically, on creation) → say what it does (sets initial attribute values) → say why that matters (the object is never usable in an incomplete state).

能得分的答题框架:说明它何时运行(创建时自动运行) → 说明它做什么(设置初始属性值) → 说明为什么重要(对象永远不会处于不完整、不可用的状态)。

✕

What a weak answer looks like: “The constructor is used to create the object when the class is called.” It names the timing but not the job. Creation is not what earns the mark, initialization is.

较弱的答案是这样的:“构造方法用于在调用类时创建对象。”它说出了时机,却没说出任务。得分的不是创建,而是初始化。

✓

What it should say: “The constructor runs automatically when a Tank is instantiated. It initializes the object's state by assigning the values passed in to attributes (self.ref, self.litres, self.target_temp) and setting is_heated to False, so no Tank can exist without a reference or a target temperature.” Timing, job, and consequence.

应该这样写:“构造方法在实例化一个 Tank 时自动运行。它通过把传入的值赋给属性(self.ref、self.litres、self.target_temp),并把 is_heated 设为 False,来初始化对象的状态,所以任何 Tank 都不可能没有编号或目标温度就存在。”时机、任务和后果都有了。

Revision questions

复习题

Past-paper style. Write an answer, then reveal the marking points and mark yourself.

仿真题风格。先写出你的答案,再显示评分要点并给自己打分。

Question 1 · 2 marks第 1 题 · 2 分

[2]Outline the role of a constructor in initializing an object's state.

[2]概述构造方法在初始化对象状态中的作用。

Question 2 · 4 marks第 2 题 · 4 分

[4]Construct a class Enclosure with attributes for a reference code, an area in square metres, and a species name, including a constructor that initializes all three.

[4]构建一个类 Enclosure,带有编号、面积(平方米)和物种名称这几个属性,并包含一个初始化这三者的构造方法。

Question 3 · 3 marks第 3 题 · 3 分

[3]Explain the difference between the parameter ref and the attribute self.ref inside a constructor.

[3]解释构造方法内部参数 ref 与属性 self.ref 的区别。

Flashcards

闪卡

Active recall for this statement’s key terms.

针对本条陈述关键术语的主动回忆。

Prototype render · content grounded in real IB CS 2027 marker-report data for B3.1.4 · not yet wired to live routes