B3.1.3 · Fundamentals of OOP for a single class
B3.1.3 · 单个类的 OOP 基础
Static and non-static variables and methods
静态与非静态变量和方法
Some data belongs to one object. Some data belongs to the whole class. Telling them apart is the entire statement.
有些数据属于某一个对象。有些数据属于整个类。把二者区分开,就是这条陈述的全部内容。
Explainer
讲解
Kestrel Cycles rents out forty bikes. Every bike has its own ID sticker and its own condition, worn brakes on one, brand new tyres on another. But every bike is rented at the same hourly rate. If that rate were stored separately inside all forty bike objects, raising the price would mean updating forty copies and hoping none were missed. Storing it once, at the level of the class itself, means one change updates every bike at once.
Kestrel Cycles 出租四十辆自行车。每辆车都有自己的编号贴纸和自己的车况,有的刹车磨损了,有的轮胎全新。但每辆车的每小时租金都是一样的。如果这个租金在四十个自行车对象里各存一份,涨价就意味着要更新四十个副本,还得祈祷没有漏掉哪一个。把它只存一次,放在类这一级,一次修改就能让每辆车同时更新。
An instance variable (non-static) belongs to one individual object. Every object created from the class gets its own separate copy, and changing one object's copy leaves every other object untouched.
实例变量(非静态)属于某一个具体的对象。由这个类创建的每个对象都有自己独立的一份副本,改动一个对象的副本,不会影响其他任何对象。
A class variable (static) belongs to the class itself, not to any object. Only one copy exists no matter how many objects are created, and every object sees that same single copy.
类变量(静态)属于类本身,而不属于任何对象。无论创建多少个对象,都只存在一份,每个对象看到的都是同一份副本。
The words static and class-level mean the same thing here, as do non-static and instance-level. Java writes the keyword static explicitly; Python marks the distinction by where the variable is written, directly inside the class body for a class variable, or on self for an instance variable.
这里 static(静态)和 class-level(类级别)是同一个意思,non-static(非静态)和 instance-level(实例级别)也是。Java 明确写出关键字 static;Python 则靠变量写在什么位置来区分:类变量直接写在类体里,实例变量则写在 self 上。
# Kestrel Cycles: what belongs to the class, and what belongs to each bike class Bike: hourly_rate = 5.00 # CLASS variable: one copy, shared by every bike total_bikes = 0 # CLASS variable: counts every Bike ever made def __init__(self, bike_id): self.bike_id = bike_id # INSTANCE variable: this bike only self.condition = "good" # INSTANCE variable: this bike only Bike.total_bikes += 1 # updates the ONE shared copy
The highlighted lines sit directly in the class body, outside any method, which is exactly what makes them class variables. The two self. lines run once per object, giving each bike its own copy.
高亮的几行直接位于类体中、任何方法之外,这正是它们成为类变量的原因。那两行 self. 在每创建一个对象时运行一次,给每辆自行车各自的一份副本。
Explainer
讲解
The same split applies to methods
方法也以同样方式划分
Methods divide the same way, and for the same reason: does this behaviour need to know which particular object it is working on?
方法按同样的方式、出于同样的理由划分:这个行为需要知道它正在处理的是哪一个具体的对象吗?
An instance method (non-static) receives the object it was called on as its first parameter, self, so it can read and change that specific object's data. It must be called on an object: bike_a.rental_cost(3).
实例方法(非静态)接收调用它的那个对象作为第一个参数 self,因此可以读取和修改那个具体对象的数据。它必须通过对象来调用:bike_a.rental_cost(3)。
A static method receives no self, so it cannot touch any individual object's data. It is called on the class itself: Bike.raise_rate(6.50). It exists inside the class because it belongs there conceptually, not because it needs an object.
静态方法不接收 self,所以不能碰任何单个对象的数据。它通过类本身来调用:Bike.raise_rate(6.50)。它放在类里,是因为在概念上属于那里,而不是因为它需要一个对象。
# both live in the Bike class, but only one of them needs a specific bike class Bike: hourly_rate = 5.00 def rental_cost(self, hours): # INSTANCE method: takes self return hours * Bike.hourly_rate @staticmethod def raise_rate(new_rate): # STATIC method: no self at all Bike.hourly_rate = new_rate
raise_rate() changes the shared rate for the whole fleet, so asking "which bike?" would make no sense. rental_cost() is written as an instance method because in a fuller version it would apply a discount based on that bike's own condition.
raise_rate() 改变的是整个车队共享的租金,所以问"哪一辆车?"没有意义。rental_cost() 写成实例方法,是因为在更完整的版本里,它会根据这辆车自己的车况给出折扣。
Explainer
讲解
Usage and scope: what each one can reach
用法与作用域:各自能访问什么
Scope is where the syllabus puts real weight, and it is not symmetrical. An instance can see everything; the class level cannot see any individual object.
考纲真正看重的是作用域,而且它并不对称。实例能看到一切;类这一级看不到任何单个对象。
| Can it reach… | 能否访问… | Instance variable / method | 实例变量 / 方法 | Class variable / static method | 类变量 / 静态方法 |
|---|---|---|---|---|---|
| Its own object's data | 自己这个对象的数据 | Yes, through self | 能,通过 self | No, there is no object to look at | 不能,因为没有可以查看的对象 |
| The shared class data | 共享的类数据 | Yes, through the class name | 能,通过类名 | Yes, that is what it works on | 能,这正是它所处理的对象 |
| How many copies exist | 存在多少份副本 | One per object created | 每创建一个对象就有一份 | Exactly one, always | 永远只有一份 |
| How it is normally called | 通常如何调用 | On an object: bike_a.method() | On the class: Bike.method() | 通过类:Bike.method() | |
| When memory is set aside | 何时分配内存 | Each time an object is created | 每次创建对象时 | Once, when the class is first loaded | 类首次加载时,只分配一次 |
An instance method can freely use class variables, because the class exists whenever an object does. A static method cannot use instance variables, because it has no idea which object you would even mean. That one-way rule explains most static-related errors.
实例方法可以随意使用类变量,因为只要有对象存在,类就存在。静态方法却不能使用实例变量,因为它根本不知道你指的是哪个对象。这条单向规则能解释大多数与 static 有关的错误。
Worked example
例题讲解
What memory actually holds, step by step
内存里究竟存了什么,一步一步看
Follow the same Kestrel Cycles class as objects get created and changed. Watch which box changes at each step: the single shared one, or one bike's own.
跟着同一个 Kestrel Cycles 类,看对象被创建和修改的过程。观察每一步是哪个方框发生了变化:是那个唯一共享的,还是某一辆车自己的。
Step 1. The class is defined. No objects exist yet, but the class variables already do, they were set aside the moment the class loaded.
第 1 步。类被定义。还没有任何对象,但类变量已经存在了,它们在类加载的那一刻就被分配好了。
Step 2. The first bike is created. It gets its own box holding its own bike_id and condition. The shared counter goes up, but notice hourly_rate is not copied into the bike's box.
第 2 步。创建第一辆自行车。它得到自己的一个方框,里面保存它自己的 bike_id 和 condition。共享的计数器增加了,但请注意 hourly_rate 没有被复制到这辆车的方框里。
Step 3. A second bike is created. A second, completely separate object box. The counter rises again, on the same single shared copy.
第 3 步。创建第二辆自行车。又一个完全独立的对象方框。计数器在那同一份共享副本上再次增加。
Step 4. Change one bike's instance variable. Only that bike's box changes. This is the behaviour students expect, and it is the easy half.
第 4 步。修改某一辆车的实例变量。只有那辆车的方框发生变化。这是学生所预期的行为,也是容易的那一半。
Step 5. Change the class variable. One assignment, and every bike in the fleet now quotes the new price, because no bike ever had its own copy to fall back on. This is the half that catches people out.
第 5 步。修改类变量。一次赋值,车队里的每辆车现在都按新价格报价,因为没有哪辆车有过自己的副本可以退回去用。这是最容易让人栽跟头的那一半。
Explainer
讲解
Choosing between them
如何在二者之间选择
The syllabus asks specifically when to use an instance variable rather than a class variable. The deciding question is short: would every object always agree on this value?
考纲特别要求说明何时应使用实例变量而不是类变量。判断的问题很简短:每个对象对这个值是否总是一致?
Real example: self.condition on each Kestrel bike, since one bike's brakes wearing out says nothing about the other thirty-nine.
实际例子:每辆 Kestrel 自行车上的 self.condition,因为一辆车的刹车磨坏了,并不说明另外三十九辆的情况。
Advantage
优点
- Each object keeps its own independent state (objects cannot corrupt each other, so a bug in handling one bike cannot silently change the rest of the fleet)
- 每个对象保留各自独立的状态 (对象之间不会互相破坏,所以处理某一辆车时出的错,不会悄悄改变车队里的其他车)
Disadvantage
缺点
- Genuinely shared values get duplicated (storing the rate on all forty bikes means forty places to update, and any missed one becomes a pricing bug that is hard to trace)
- 真正共享的值被重复存储 (把租金存在全部四十辆车上,意味着有四十个地方要更新,漏掉任何一个都会变成难以追查的价格错误)
Real example: Bike.hourly_rate, one price the whole fleet is rented at, and Bike.total_bikes, a count that belongs to no single bike.
实际例子:Bike.hourly_rate,整个车队统一的租赁价格,以及 Bike.total_bikes,一个不属于任何一辆车的计数。
Advantage
优点
- One value, updated in exactly one place (a price change is a single assignment that every existing and future object picks up automatically)
- 一个值,只在一个地方更新 (涨价只是一次赋值,所有现有的和将来的对象都会自动采用)
Disadvantage
缺点
- Every object is affected by any change (code anywhere in the program can change it, and a value that later needs to differ per object requires redesigning the class)
- 任何改动都会影响每一个对象 (程序中任何地方的代码都可以修改它,而如果将来某个值需要因对象而异,就得重新设计这个类)
The rule of thumb: use an instance variable by default, and reach for a class variable only when the value genuinely describes the class as a whole, a shared rate, a running count of objects, or a fixed constant. A value that might one day differ per object should start as an instance variable.
经验法则:默认使用实例变量,只有当这个值确实描述整个类时,才使用类变量,比如共享的租金、对象的累计数量,或固定的常量。一个将来可能因对象而异的值,应当一开始就做成实例变量。
Try it yourself
动手试试
Run the Kestrel Cycles class
运行 Kestrel Cycles 类
The same class from the stepper, live and editable. Try changing bike_a.hourly_rate = 9.00 instead of Bike.hourly_rate, that single character difference creates a brand new instance variable that shadows the shared one for that bike alone, which is exactly the trap in the mistake callout below.
和步进器里是同一个类,可在线编辑运行。试着把 Bike.hourly_rate 改成 bike_a.hourly_rate = 9.00,这一个字符的差别会创建一个全新的实例变量,只为这一辆车遮蔽共享的那个,这正是下面常见错误提示框里的陷阱。
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 class variables and static methods, but it isn't full Python: one visible difference is that whole-number floats print as 5 here rather than Python's 5.0.
正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括类变量和静态方法,但它不是完整的 Python:一个明显的差别是,整数值的浮点数在这里打印为 5,而不是 Python 的 5.0。
Check your understanding
检查你的理解
Two Bike objects exist. A program runs bike_a.hourly_rate = 9.00, then prints bike_b.hourly_rate. What is printed, and why?
存在两个 Bike 对象。程序运行 bike_a.hourly_rate = 9.00,然后打印 bike_b.hourly_rate。会打印什么,为什么?
Common mistake
常见错误
B3.1.3B3.1.3 的这一常见模式RecurringCandidates describe a class variable as being "shared" without stating the point that earns the mark: only one copy exists in memory, so there is nothing per-object to update. Answers that stop at "all objects can use it" describe access, not storage, and read as vague.
反复出现考生把类变量描述为"共享的",却没有说出能得分的那一点:内存中只有一份副本,所以没有任何"每个对象各自的东西"需要更新。止于"所有对象都能使用它"的答案描述的是访问,而不是存储,读起来很含糊。
The second recurring error is writing to a class variable through an object. In Python this quietly creates a new instance variable that hides the shared one for that object, so the program keeps running and produces wrong values with no error message at all.
第二个反复出现的错误,是通过对象去写类变量。在 Python 中,这会悄悄创建一个新的实例变量,为那个对象遮蔽共享的变量,于是程序照常运行,却产生错误的值,而且没有任何错误提示。
Answer frame that scores: say how many copies exist → say who they belong to → state the consequence of changing one.
能得分的答题框架:说明存在多少份副本 → 说明它们属于谁 → 陈述改动其中一份的后果。
What a weak answer looks like: “A static variable is shared between all the objects of the class.” True but thin: it never says only one copy exists, and never says what happens when it changes.
较弱的答案是这样的:“静态变量由这个类的所有对象共享。”没错但太单薄:它没有说只存在一份副本,也没有说改动它会发生什么。
What it should say: “A static variable has exactly one copy, stored with the class rather than with any object, so all forty bikes read that same copy. Changing Bike.hourly_rate once changes the price every bike reports, whereas each bike's condition is an instance variable with its own copy per object.” Copies counted, owner named, consequence stated.
应该这样写:“静态变量恰好有一份副本,存储在类中而不是任何对象里,所以四十辆车读取的都是同一份副本。修改一次 Bike.hourly_rate,每辆车报出的价格就都改变了,而每辆车的 condition 是实例变量,每个对象各有一份副本。”数出了副本数量,指明了归属,陈述了后果。
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[2]Distinguish between a static variable and an instance variable.
[2]区分静态变量和实例变量。
Marking points
评分要点
- A static (class) variable belongs to the class and there is one shared copy that every instance sees.
- An instance variable belongs to each object separately, so every object has its own independent value.
- 静态(类)变量属于类,只有一份共享的副本,每个实例都看到它。
- 实例变量分别属于每个对象,所以每个对象都有自己独立的值。
[3]A Bike class stores hourly_rate as a class variable. Explain one advantage and one disadvantage of this decision.
[3]一个 Bike 类把 hourly_rate 存为类变量。解释这个决定的一个优点和一个缺点。
Marking points
评分要点
- Advantage: the hourly rate is stored once, so updating it changes the rate for every bike consistently and there is no risk of copies disagreeing.
- Disadvantage: every bike is forced to share the same rate, so if one bike ever needs a different rate the design has to change.
- It also uses slightly less memory than storing the rate on every instance.
- 优点:每小时费率只存一次,所以更新它会一致地改变每辆车的费率,不会出现副本互相矛盾。
- 缺点:每辆车都被迫共享同一费率,所以如果某辆车需要不同的费率,设计就必须改变。
- 它也比在每个实例上存费率略微少用一点内存。
[3]A developer adds a static method to Bike and tries to read self.condition inside it. Explain why this cannot work.
[3]一位开发者给 Bike 添加了一个静态方法,并试图在其中读取 self.condition。解释为什么这行不通。
Marking points
评分要点
- A static method belongs to the class, not to any object, so it is not given a self parameter.
- self.condition refers to an instance variable, which exists only on a particular object.
- Inside a static method there is no instance, so there is nothing for self to refer to and the access fails.
- To read condition the method would need to be an instance method (taking self), or be passed a Bike object explicitly.
- 静态方法属于类,不属于任何对象,所以它没有 self 参数。
- self.condition 指的是一个实例变量,它只存在于某个特定的对象上。
- 在静态方法内部没有实例,所以 self 无所指代,访问失败。
- 要读取 condition,该方法需要是一个实例方法(接受 self),或被显式传入一个 Bike 对象。
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.3, and every other IB CS 2027 statement.
免费账号:解锁 B3.1.3 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。