High School Computer Science

Object-Oriented Programming (Intro)面向对象编程(入门)

Object-oriented programming (OOP) is a way of organising code around objects, bundles that combine data (attributes) and behaviour (methods) into a single unit. You define a class as the blueprint, then create as many instances as you need. A Dog class describes what every dog has and can do; each individual dog (Fido, Bella) is a separate object. This guide covers Python OOP from scratch: defining classes, writing instance variables, calling methods, building constructors with __init__, and a first look at encapsulation and inheritance. All code is Python; it feeds directly into AP CSA Java classes.面向对象编程(OOP,object-oriented programming)是一种将代码围绕对象(object)组织的方式,对象将数据(属性 attribute)和行为(方法 method)捆绑为一个单元。你把类(class)定义为蓝图,然后按需创建任意数量的实例(instance)。Dog 类描述每条狗拥有什么、能做什么;每条具体的狗(Fido、Bella)是独立的对象。本指南从零开始讲授 Python OOP:定义类、编写实例变量、调用方法、用 __init__ 构建构造函数(constructor),以及初步了解封装(encapsulation)与继承(inheritance)。全部代码为 Python,直接为 AP CSA Java 类打基础。

7 sections7 节内容 CSTA 3B · ON ICS4U · BC CP12 · AB CSE3120CSTA 3B · ON ICS4U · BC CP12 · AB CSE3120 Python code worked examplesPython 代码例题 Honors / Advanced荣誉 / 进阶

What is OOP? Objects and Classes什么是面向对象编程?对象与类

Learning objectives学习目标
  • State what a class and an object (instance) are, and give a real-world example of each.
  • Compare a procedural model and an object-oriented model of the same data (Worked Example 1).
  • Explain why two objects with equal attributes are still different objects, and what b = a does (Worked Example 2).
  • Use is, == and isinstance to test identity, equality and class membership (Worked Example 2).
  • 说出类和对象(实例)是什么,并各举一个现实例子。
  • 比较同一批数据的过程式模型与面向对象模型(例题 1)。
  • 解释为什么属性相同的两个对象仍是不同的对象,以及 b = a 做了什么(例题 2)。
  • 用 is、== 和 isinstance 检验同一性、相等和类归属(例题 2)。
Three core ideas: memorise these first.三个核心概念:先背会这些。
  • Class类(class): the blueprint or template. Defines what data and behaviours all objects of this type share. A Dog class says "every dog has a name and an age and can bark." CSE3120 outcome 1.1.5: "use of classes and objects.":蓝图或模板。定义该类型所有对象共有的数据和行为。Dog 类说明"每条狗都有名字和年龄,都能叫。" CSE3120 结果 1.1.5:"类和对象的使用。"
  • Object / Instance对象 / 实例(object / instance): a concrete realisation of the class blueprint. fido = Dog("Fido", 3) creates one specific dog object. Each object has its own copy of the data.:类蓝图的具体实现。fido = Dog("Fido", 3) 创建一个具体的狗对象。每个对象都有自己的数据副本。
  • Real-world modelling现实世界建模(real-world modelling): OOP maps naturally to real things: a BankAccount has a balance and an owner and can deposit/withdraw. ICS4U C1.1: "decompose a problem into modules, classes, or abstract data types using an object-oriented design methodology.":OOP 自然地映射到现实事物:BankAccount 有余额和所有者,能存款/取款。ICS4U C1.1:"使用面向对象设计方法将问题分解为模块、类或抽象数据类型。"
The key insight: instead of writing separate variables dog1_name, dog1_age, dog2_name, dog2_age …, you define a Dog class once and create as many dog objects as you need. Each object is self-contained.关键洞见:不必写分散的变量 dog1_name、dog1_age、dog2_name、dog2_age……,只需定义一次 Dog 类,然后按需创建任意数量的狗对象。每个对象都是自包含的。
Worked Example 1: Comparing procedural vs OOP style例题 1:过程式与面向对象风格对比

Model two dogs (Fido age 3, Bella age 5). Show the difference between procedural (separate variables) and OOP (class instance) approaches.建模两条狗(Fido 3 岁,Bella 5 岁)。展示过程式(分散变量)与面向对象(类实例)方式的区别。

Procedural approach (messy, hard to scale).过程式方式(混乱,难以扩展)。

dog1_name = "Fido"
dog1_age  = 3
dog2_name = "Bella"
dog2_age  = 5
# Adding dog3 means adding two more variables...
Procedural: each dog needs multiple separate variables; the code grows out of control as the number of dogs increases.过程式:每条狗需要多个独立变量,数量增加时代码迅速失控。

OOP approach (clean, scalable).面向对象方式(简洁,可扩展)。

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age  = age

fido  = Dog("Fido",  3)
bella = Dog("Bella", 5)
print(fido.name, fido.age)   # Fido 3
print(bella.name, bella.age) # Bella 5
OOP: the Dog class is defined once; fido and bella are independent instances, each holding their own name and age.面向对象:Dog 类定义一次;fido 和 bella 是各自独立的实例(instance,实例),各自持有自己的 name 和 age。

The Dog class is defined once. fido and bella are separate instances, each with their own data. Adding a third dog is one line: rex = Dog("Rex", 2).只需一行就能添加第三条狗:rex = Dog("Rex", 2)。

Worked Example 2: One object, two names (aliasing)例题 2:一个对象,两个名字(别名)

Create two Dog objects with identical data and a third name for the first. Show whether they are equal, whether they are the same object, and what happens when you change the age through the third name.创建两个数据完全相同的 Dog 对象,再给第一个对象起第三个名字。说明它们是否相等、是否为同一对象,以及通过第三个名字修改年龄会发生什么。

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age  = age

a = Dog("Rex", 4)
b = Dog("Rex", 4)
c = a                       # c is another name for the same object

print(a == b, a is b, a is c)   # False False True
c.age = 5
print(a.age, b.age)             # 5 4
print(isinstance(a, Dog), isinstance("Rex", Dog))   # True False

a and b hold the same data, but Dog("Rex", 4) ran twice and built two objects. A class with no __eq__ method compares by identity, so a == b is False and a is b is False. The line c = a does not build anything: it gives the existing object a second name, so a is c is True. Changing c.age changes the one shared object, which is why a.age becomes 5 while b.age stays 4.a 和 b 的数据相同,但 Dog("Rex", 4) 运行了两次,造出了两个对象。没有定义 __eq__ 方法的类按同一性比较,所以 a == b 为 False,a is b 也为 False。c = a 不会造新对象,只是给已有对象起第二个名字,所以 a is c 为 True。修改 c.age 改的是那个共享的对象,因此 a.age 变为 5,而 b.age 仍是 4。

isinstance(obj, Class) asks whether the object was built from that class (or from a subclass of it). isinstance(a, Dog) is True; a string is not a Dog, so the second test is False.isinstance(对象, 类) 检查对象是否由该类(或其子类)创建。isinstance(a, Dog) 为 True;字符串不是 Dog,所以第二个检验为 False。

In OOP, what is a class?在面向对象编程中,什么是类(class)?
§1 · Q1
A specific object with its own data拥有自身数据的具体对象
A function that returns a value返回值的函数
A blueprint that defines the data and behaviour shared by all objects of that type定义该类型所有对象共有数据和行为的蓝图
A list of variables变量列表
A class is the blueprint or template. It defines what attributes (data) and methods (behaviour) every object of that type will have. Each actual object is an instance of the class.类是蓝图或模板。它定义该类型每个对象将拥有的属性(数据)和方法(行为)。每个实际对象都是该类的一个实例。
A specific object with its own data is an instance, not the class. The class is the blueprint; instances are created from it.拥有自身数据的具体对象是实例,而非类。类是蓝图;实例从蓝图创建。
You define a Car class and then write my_car = Car("Toyota", 2022). What is my_car?你定义了一个 Car 类,然后写了 my_car = Car("Toyota", 2022)。my_car 是什么?
§1 · Q2
The class definition类的定义
A function一个函数
A variable storing a string存储字符串的变量
An instance (object) of the Car classCar 类的一个实例(对象)
my_car is an instance of the Car class, a concrete object created from the blueprint. It has its own copy of the data ("Toyota", 2022).my_car 是 Car 类的一个实例,从蓝图创建的具体对象。它拥有自己的数据副本("Toyota",2022)。
Calling Car(...) creates an instance (object), not the class itself. The class is defined with the class keyword above.调用 Car(...) 创建一个实例(对象),而不是类本身。类是用上方的 class 关键字定义的。
Exam tip考试提示

Command words here are state, explain and trace. When a question asks you to distinguish a class from an object, name both and give a sentence with an example: "Dog is the class; fido is an instance of it." Common error: writing that b = a makes a copy. It creates a second name for one object, so a change through either name is visible through both.

本节的指令词是说出(state)、解释(explain)和追踪(trace)。题目要求区分类和对象时,两者都要点名并给出例句:"Dog 是类;fido 是它的一个实例。"常见错误:写成 b = a 会复制对象。它只是给同一个对象起了第二个名字,通过任一名字所做的修改,另一个名字也看得到。

Check your understanding自我检测
Given the Dog class from Worked Example 1, what does p = Dog("Pip", 2); q = p; q.age = 3; print(p.age) print?已知例题 1 中的 Dog 类,p = Dog("Pip", 2); q = p; q.age = 3; print(p.age) 打印什么?

It prints 3. q = p gives the one Dog object a second name, so setting q.age changes the object that p also names.

打印 3。q = p 给唯一的 Dog 对象起了第二个名字,所以设置 q.age 改变的也是 p 所指的对象。

For each item say whether it is a class or an instance: Dog, fido, Dog("Rex", 4), BankAccount.判断下列各项是类还是实例:Dog、fido、Dog("Rex", 4)、BankAccount。

Dog is a class (the blueprint). fido is a name that refers to an instance. Dog("Rex", 4) is an expression that creates a new instance. BankAccount is a class.

Dog 是类(蓝图)。fido 是指向某个实例的名字。Dog("Rex", 4) 是创建新实例的表达式。BankAccount 是类。

Trace d1 = Dog("A", 1); d2 = Dog("A", 1); d3 = d1; d3.name = "B"; print(d1.name, d2.name, d1 is d3, d1 == d2) and explain each value.追踪 d1 = Dog("A", 1); d2 = Dog("A", 1); d3 = d1; d3.name = "B"; print(d1.name, d2.name, d1 is d3, d1 == d2) 并解释每个值。

It prints B A True False. d3 and d1 name one object, so renaming through d3 gives d1.name == "B". d2 is a separate object, so its name is still "A". d1 is d3 is True (same object). d1 == d2 is False because the class defines no equality, so Python falls back to identity.

输出 B A True False。d3 和 d1 指向同一个对象,所以通过 d3 改名后 d1.name == "B"。d2 是另一个对象,名字仍是 "A"。d1 is d3 为 True(同一对象)。d1 == d2 为 False,因为类没有定义相等比较,Python 退回到按同一性比较。

Going deeper: OOP vs procedural paradigms (CSE3120 1.1 / ICS4U C1)深入:面向对象与过程式范式对比(CSE3120 1.1 / ICS4U C1)

CSE3120 outcome 1.1.1 describes OOP as "implementation by the exchange of 'messages' among 'objects'." In practice this means calling methods on objects: fido.bark() sends a "bark" message to the fido object. ICS4C A3.4 (verbatim): "compare and contrast object-oriented and procedural programming paradigms." Procedural code is a sequence of function calls acting on separate data; OOP bundles data and the functions that operate on it together. The bundling is called encapsulation, covered in §7.CSE3120 结果 1.1.1 将 OOP 描述为"通过'对象'间'消息'交换实现"。实际上这意味着在对象上调用方法:fido.bark() 向 fido 对象发送"bark"消息。ICS4C A3.4(原文):"比较和对比面向对象与过程式编程范式。"过程式代码是一系列作用于独立数据的函数调用;OOP 将数据和操作数据的函数捆绑在一起。这种捆绑称为封装,在 §7 中介绍。


Defining a Class定义类

Learning objectives学习目标
  • Write a class header, an __init__ method and one more method, using CapWords for the class name and self as the first parameter.
  • Explain what self refers to in s1.is_passing() and s2.is_passing(), and show that Student.is_passing(s1) is the same call (Worked Example 4).
  • Distinguish __str__ (readable, used by print) from __repr__ (unambiguous, shown inside lists) (Worked Example 4).
  • Predict the error caused by a method that leaves out self (check question 2).
  • 写出类头、__init__ 方法和另一个方法,类名用 CapWords,第一个参数用 self。
  • 解释 s1.is_passing() 和 s2.is_passing() 中 self 指代什么,并说明 Student.is_passing(s1) 是同一个调用(例题 4)。
  • 区分 __str__(便于阅读,供 print 使用)与 __repr__(明确无歧义,列表中显示的形式)(例题 4)。
  • 预测漏写 self 的方法所引发的错误(自我检测第 2 题)。
Python class skeleton: memorise this structure.Python 类骨架:背熟这个结构。
class ClassName:
    def __init__(self, param1, param2):
        self.attr1 = param1
        self.attr2 = param2

    def method_name(self):
        # body
        pass
  • class ClassName: declares the class. Convention: CapWords (PascalCase). E.g. BankAccount, StudentRecord.声明类。惯例:大写驼峰(PascalCase)。如 BankAccount、StudentRecord。
  • def __init__(self, ...): the constructor; called automatically when you create a new object. Sets up the object's initial data. Covered in depth in §5.构造函数(constructor,构造函数);创建新对象时自动调用,设置对象的初始数据。在 §5 中深入介绍。
  • self: the first parameter of every method; it refers to the current object. Python passes it automatically; you do not pass it when calling the method.:每个方法的第一个参数;指代当前对象。Python 自动传递 self,调用方法时无需手动传入。
Worked Example 3: A Student class例题 3:Student 类

Define a Student class with a name and a grade (0–100). Add a method is_passing() that returns True if grade ≥ 50.定义一个 Student 类,包含姓名和成绩(0–100)。添加方法 is_passing(),如果成绩 ≥ 50 则返回 True。

class Student:
    def __init__(self, name, grade):
        self.name  = name
        self.grade = grade

    def is_passing(self):
        return self.grade >= 50

# Create two instances
s1 = Student("Alice", 78)
s2 = Student("Bob",   42)

print(s1.name, s1.is_passing())   # Alice True
print(s2.name, s2.is_passing())   # Bob   False
Code notes: class Student: defines the class; def __init__(self, name, grade): is the constructor; self.name and self.grade are instance attributes; def is_passing(self): is an instance method; s1 = Student("Alice", 78) creates an instance.代码注解:class Student: 定义类;def __init__(self, name, grade): 构造函数,self.name 和 self.grade 是实例属性(instance variable,实例变量);def is_passing(self): 是实例方法;s1 = Student("Alice", 78) 创建实例。

Key points: (1) self.name and self.grade are stored per-object; s1 and s2 each have their own copies. (2) is_passing() uses self.grade to access the current object's data. (3) You call the method as s1.is_passing(), not Student.is_passing(s1) (Python does that internally).要点:(1) self.name 和 self.grade 按对象存储,s1 和 s2 各有自己的副本。(2) is_passing() 用 self.grade 访问当前对象的数据。(3) 调用方式为 s1.is_passing(),而非 Student.is_passing(s1)(Python 在内部完成这一步)。

Worked Example 4: Printing an object: __str__ and __repr__例题 4:打印对象:__str__ 与 __repr__

Give the Student class a readable text form for print and an unambiguous form for debugging. Show what print(s), print([s]) and repr(s) display, and show that Student.is_passing(s) and s.is_passing() are the same call.为 Student 类提供供 print 使用的易读文本形式和供调试用的明确形式。展示 print(s)、print([s]) 和 repr(s) 的显示结果,并说明 Student.is_passing(s) 与 s.is_passing() 是同一个调用。

class Student:
    def __init__(self, name, grade):
        self.name  = name
        self.grade = grade

    def __str__(self):                 # readable, for print(s) and str(s)
        return f"{self.name} ({self.grade})"

    def __repr__(self):                # unambiguous, for repr(s) and lists
        return f"Student({self.name!r}, {self.grade})"

    def is_passing(self):
        return self.grade >= 50

s = Student("Alice", 78)
print(s)                                # Alice (78)
print([s])                              # [Student('Alice', 78)]
print(repr(s))                          # Student('Alice', 78)
print(Student.is_passing(s) == s.is_passing())   # True

print(s) calls __str__, so it shows the friendly text Alice (78). A list does not use __str__ for its items: it shows each item with __repr__, so print([s]) gives [Student('Alice', 78)]. The !r inside the f-string asks for the repr of the name, which is why the name appears in quotes. If a class defines neither method, print(obj) shows a default such as <__main__.Student object at 0x...>, whose address differs on every run.print(s) 调用 __str__,所以显示友好的文本 Alice (78)。列表显示其元素时不用 __str__,而用 __repr__,所以 print([s]) 得到 [Student('Alice', 78)]。f 字符串中的 !r 要求取姓名的 repr,因此姓名带引号。如果类两个方法都没定义,print(obj) 显示默认形式,如 <__main__.Student object at 0x...>,其地址每次运行都不同。

The last line shows what self is: s.is_passing() is shorthand for Student.is_passing(s). Python looks up the method in the class and passes s as the first argument, which the method names self.最后一行说明了 self 是什么:s.is_passing() 是 Student.is_passing(s) 的简写。Python 在类中查找方法,并把 s 作为第一个实参传入,方法把它命名为 self。

What naming convention does Python use for class names?Python 类名使用什么命名惯例?
§2 · Q1
CapWords / PascalCase (e.g. BankAccount)大写驼峰 / PascalCase(如 BankAccount)
snake_case (e.g. bank_account)下划线命名(如 bank_account)
ALL_CAPS (e.g. BANKACCOUNT)全大写(如 BANKACCOUNT)
camelCase (e.g. bankAccount)小驼峰(如 bankAccount)
Python convention (PEP 8): class names use CapWords (PascalCase), each word capitalised, no underscores. Functions and variables use snake_case; constants use ALL_CAPS.Python 惯例(PEP 8):类名使用 CapWords(PascalCase),每个单词首字母大写,无下划线。函数和变量用 snake_case;常量用 ALL_CAPS。
Class names use CapWords/PascalCase. Functions and variables use snake_case. Constants use ALL_CAPS.类名用 CapWords/PascalCase。函数和变量用 snake_case。常量用 ALL_CAPS。
In the Student example, what does self refer to inside is_passing()?在 Student 例子中,is_passing() 内部的 self 指代什么?
§2 · Q2
The Student class itselfStudent 类本身
The specific object on which the method was called调用该方法的具体对象
The first argument passed by the caller调用者传入的第一个实参
A copy of the object对象的副本
self refers to the specific object that the method was called on. When you write s1.is_passing(), self inside the method is s1. When you write s2.is_passing(), self is s2.self 指代调用该方法的具体对象。写 s1.is_passing() 时,方法内部的 self 就是 s1;写 s2.is_passing() 时,self 就是 s2。
self is not the class itself; it is the instance. It lets the method access the current object's own data via self.attribute.self 不是类本身,而是实例。它让方法通过 self.属性 访问当前对象自己的数据。
Exam tip考试提示

Command words: write a class, trace a call, explain self. Check three things before you submit a class: the header ends with a colon, every method lists self first, and every attribute inside a method is written self.name. Common errors: def is_passing(): with no self (the call fails with a TypeError because Python passes one argument the method does not accept) and return grade >= 50 without self. (a NameError).

指令词:编写(write)类、追踪(trace)调用、解释(explain)self。提交类之前检查三点:类头以冒号结尾;每个方法第一个参数是 self;方法内每个属性都写成 self.名称。常见错误:写成 def is_passing(): 漏掉 self(调用时 Python 传入一个方法不接受的实参,引发 TypeError),以及写成 return grade >= 50 漏掉 self.(引发 NameError)。

Check your understanding自我检测
A class defines __repr__ returning Student('Alice', 78) but no __str__. What does print(s) show?一个类定义了返回 Student('Alice', 78) 的 __repr__,但没有定义 __str__。print(s) 显示什么?

It shows Student('Alice', 78). When a class has no __str__, print and str() fall back to __repr__. The reverse does not hold: a class with only __str__ still shows the default address form inside a list.

显示 Student('Alice', 78)。类没有 __str__ 时,print 和 str() 退而使用 __repr__。反过来则不成立:只有 __str__ 的类,在列表中仍显示默认的地址形式。

A learner writes def is_passing(): return grade >= 50 inside Student and calls s1.is_passing(). What happens, and what are the two fixes?一位学习者在 Student 中写了 def is_passing(): return grade >= 50,然后调用 s1.is_passing()。会发生什么?两处修正是什么?

Python raises a TypeError: the call passes s1 automatically, but the method is defined with 0 parameters. Fix 1: add self to the parameter list. Fix 2: read the attribute as self.grade, because a bare grade is not defined inside the method.

Python 引发 TypeError:调用时自动传入 s1,但方法定义的参数个数为 0。修正 1:在参数列表中加入 self。修正 2:把属性写成 self.grade,因为方法内部没有定义单独的 grade。

Write a Book class with attributes title and pages and a method is_long() that returns True when there are more than 300 pages. Create Book("Dune", 612) and print its title and is_long().编写 Book 类,属性为 title 和 pages,方法 is_long() 在页数多于 300 时返回 True。创建 Book("Dune", 612) 并打印其 title 和 is_long()。

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def is_long(self):
        return self.pages > 300

b = Book("Dune", 612)
print(b.title, b.is_long())   # Dune True
The class name is CapWords, every method starts with self, and the method returns a value instead of printing it.

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def is_long(self):
        return self.pages > 300

b = Book("Dune", 612)
print(b.title, b.is_long())   # Dune True
类名用 CapWords,每个方法以 self 开头,方法用返回值而不是打印来给出结果。


Attributes (Instance Variables)属性(实例变量)

Learning objectives学习目标
  • Define an instance attribute and create it with self.attr = value inside __init__.
  • Predict that changing one object's attribute leaves other objects unchanged (Worked Example 5).
  • Distinguish a class attribute (shared, written in the class body) from an instance attribute (one per object) (Worked Example 6).
  • Explain the shared mutable class attribute trap and fix it by creating the list inside __init__ (Worked Example 6).
  • Explain why assigning obj.attr = value creates an instance attribute that hides a class attribute of the same name (Worked Example 6).
  • 定义实例属性,并在 __init__ 内用 self.attr = value 创建它。
  • 预测修改一个对象的属性不会影响其他对象(例题 5)。
  • 区分类属性(共享,写在类体中)与实例属性(每个对象一份)(例题 6)。
  • 解释共享可变类属性的陷阱,并通过在 __init__ 中创建列表来修正(例题 6)。
  • 解释为什么给 obj.attr 赋值会创建一个遮蔽同名类属性的实例属性(例题 6)。
Attributes are the data each object carries: three things to know.属性是每个对象携带的数据:记住这三点。
  • Defined with self.attr = value用 self.attr = value 定义: always inside __init__. Every object of the class then has its own copy of that attribute. ICS4C B2.1: "create and use instance methods (e.g., constructors, mutators, accessors).":总是在 __init__ 内部定义。该类的每个对象都有自己的属性副本。ICS4C B2.1:"创建和使用实例方法(如构造函数、修改器、访问器)。"
  • Per-instance (not shared)每个实例独立(不共享): changing s1.grade does not affect s2.grade. Each object's attributes are independent. This is the core benefit of OOP over global variables.:修改 s1.grade 不影响 s2.grade。每个对象的属性是独立的。这是 OOP 相较于全局变量的核心优势。
  • Access with dot notation: object.attribute用点号访问:对象.属性: s1.name reads Alice's name; s1.name = "Alicia" updates it. CSE3120 1.1.3: "use of private, public and protected members, accessors and modifiers to control access to data.":s1.name 读取 Alice 的姓名;s1.name = "Alicia" 更新它。CSE3120 1.1.3:"使用私有、公有和受保护成员、访问器和修改器来控制数据访问。"
Worked Example 5: BankAccount with balance attribute例题 5:带余额属性的 BankAccount

Define a BankAccount class with owner and balance attributes. Create two accounts and show that their balances are independent.定义一个 BankAccount 类,包含 owner(所有者)和 balance(余额)属性。创建两个账户并证明它们的余额是独立的。

class BankAccount:
    def __init__(self, owner, balance):
        self.owner   = owner
        self.balance = balance

acc1 = BankAccount("Alice", 1000)
acc2 = BankAccount("Bob",    500)

acc1.balance += 200          # deposit $200 into Alice's account
print(acc1.owner, acc1.balance)  # Alice 1200
print(acc2.owner, acc2.balance)  # Bob    500  (unchanged)
Code notes: self.owner and self.balance are instance variables. acc1 and acc2 are independent objects. Changing acc1.balance does not affect acc2.balance.代码注解:self.owner 和 self.balance 是实例变量(instance variable,实例变量),acc1 与 acc2 各自独立。修改 acc1.balance 不影响 acc2.balance。

Notice: acc1.balance += 200 modifies only Alice's account object. Bob's account is completely separate in memory. With a handful of separate global variables this separation is easy to break and hard to scale.注意:acc1.balance += 200 只修改 Alice 的账户对象。Bob 的账户在内存中完全独立。用零散的全局变量很难保持这种隔离,也难以扩展。

Worked Example 6: Class attribute vs instance attribute (the shared list trap)例题 6:类属性与实例属性(共享列表陷阱)

A Dog class stores a species shared by all dogs and a list of tricks for each dog. Show what goes wrong when the list is written in the class body, then fix it.Dog 类保存所有狗共有的 species,以及每条狗各自的 tricks 列表。展示把列表写在类体中会出什么问题,然后修正。

Buggy version: the list is a class attribute.有缺陷的版本:列表是类属性。

class Dog:
    species = "Canis familiaris"   # class attribute: one value for the whole class
    tricks  = []                   # class attribute: ONE list shared by every dog

    def __init__(self, name):
        self.name = name

    def add_trick(self, trick):
        self.tricks.append(trick)  # finds the shared list through the class

rex = Dog("Rex")
pip = Dog("Pip")
rex.add_trick("sit")
print(pip.tricks)                  # ['sit']   (Pip learned nothing)
print(Dog.tricks is rex.tricks)    # True      (one list, two ways to reach it)

pip.species = "wolf"               # creates an instance attribute on pip only
print(rex.species, pip.species, Dog.species)   # Canis familiaris wolf Canis familiaris
print("species" in vars(rex), "species" in vars(pip))   # False True

self.tricks.append(...) does not assign to self.tricks: it looks up tricks, finds it on the class because the object has none, and changes that one list in place. Every dog therefore shares it. Assignment is different: pip.species = "wolf" creates a new instance attribute on pip, which hides the class attribute for pip only. vars(obj) lists an object's own attributes, which confirms that only pip has species.self.tricks.append(...) 并不是对 self.tricks 赋值:它查找 tricks,因为对象自己没有,就在类上找到并原地修改那一个列表,所以每条狗共享它。赋值则不同:pip.species = "wolf" 在 pip 上创建新的实例属性,只对 pip 遮蔽类属性。vars(obj) 列出对象自己的属性,可以确认只有 pip 拥有 species。

Fixed version: the list is an instance attribute.修正后的版本:列表是实例属性。

class Dog:
    species = "Canis familiaris"   # shared on purpose: constant for the whole class

    def __init__(self, name):
        self.name = name
        self.tricks = []           # a new list for each object

    def add_trick(self, trick):
        self.tricks.append(trick)

rex = Dog("Rex")
pip = Dog("Pip")
rex.add_trick("sit")
print(rex.tricks, pip.tricks)      # ['sit'] []

Rule of thumb: put a value in the class body only if every object should share it and it is not changed (a constant such as species). Anything that belongs to one object, especially a list or dictionary, is created with self. inside __init__.经验法则:只有每个对象都应共享、且不会被修改的值(如常量 species)才放在类体中。属于单个对象的东西,尤其是列表或字典,要在 __init__ 内用 self. 创建。

After a = Dog("Rex", 4) and b = Dog("Pip", 2), you run a.age = 5. What is b.age?执行 a = Dog("Rex", 4) 和 b = Dog("Pip", 2) 后,运行 a.age = 5。b.age 是多少?
§3 · Q1
5
4
2
Error: attribute does not exist错误:属性不存在
Instance attributes are per-object. Changing a.age has no effect on b.age. b was created with age 2, and that value is unchanged. b.age is still 2.实例属性是每个对象独立的。修改 a.age 对 b.age 没有影响。b 创建时 age 为 2,该值未改变。b.age 仍然是 2。
Each object has its own copy of every instance attribute. Changing one object's attribute never affects another object's attribute.每个对象都有自己的每个实例属性副本。改变一个对象的属性永远不会影响另一个对象的属性。
Where should instance attributes be defined in a Python class?在 Python 类中,实例属性应该在哪里定义?
§3 · Q2
At the top of the file, outside the class在文件顶部,类的外部
Inside any method, without self.任何方法内部,不加 self.
In a separate function outside the class在类外部的独立函数中
Inside __init__ using self.attribute = value在 __init__ 内使用 self.属性 = 值
Instance attributes are defined inside __init__ using self.attribute = value. This ensures every new object gets its own copy of each attribute when it is created.实例属性在 __init__ 内使用 self.属性 = 值 定义。这确保每个新对象在创建时都能获得每个属性的自己副本。
Variables defined without self. inside a method are local variables, not instance attributes. Instance attributes require self. and are typically set in __init__.在方法内部不加 self. 定义的变量是局部变量,而非实例属性。实例属性需要 self.,通常在 __init__ 中设置。
Exam tip考试提示

Command words: trace, predict, identify the error. For a class attribute question, find where each name is assigned: in the class body (shared by all objects) or after self. in a method (one per object). Common errors: writing a list or dictionary in the class body and expecting each object to get its own, and expecting obj.attr = value to change the class attribute (it creates an instance attribute instead; use ClassName.attr = value to change the shared one).

指令词:追踪(trace)、预测(predict)、找出错误(identify the error)。遇到类属性的题目,先看每个名字在哪里赋值:在类体中(所有对象共享),还是在方法中 self. 之后(每个对象一份)。常见错误:把列表或字典写在类体中,却以为每个对象各有一份;以及以为 obj.attr = value 会改变类属性(它其实创建了实例属性;要改共享的值,用 类名.attr = value)。

Check your understanding自我检测
A class Counter has count = 0 in its body, and its __init__ runs Counter.count += 1. Three objects are created. What is Counter.count? What would self.count += 1 have done instead?类 Counter 的类体中有 count = 0,其 __init__ 执行 Counter.count += 1。创建了三个对象。Counter.count 是多少?若改成 self.count += 1 会怎样?

Counter.count is 3, because each constructor call updates the one shared class attribute. With self.count += 1, Python reads the class value 0, adds 1, and stores 1 as a new instance attribute on that object. Each object would then show count == 1 while Counter.count stayed 0.

Counter.count 是 3,因为每次调用构造函数都更新那一个共享的类属性。若用 self.count += 1,Python 读取类属性 0,加 1 后把 1 存为该对象的新实例属性。这样每个对象的 count == 1,而 Counter.count 仍为 0。

A class Bag has items = [] in its body and a method add(self, x) that runs self.items.append(x). After b1, b2 = Bag(), Bag(), b1.add(1) and b2.add(2), what is b1.items? How do you fix the class?类 Bag 的类体中有 items = [],方法 add(self, x) 执行 self.items.append(x)。在 b1, b2 = Bag(), Bag()、b1.add(1) 和 b2.add(2) 之后,b1.items 是什么?如何修正这个类?

b1.items is [1, 2]: both objects use the same class-level list. Fix: remove items = [] from the class body and write self.items = [] inside __init__, so each object gets its own list.

b1.items 是 [1, 2]:两个对象使用同一个类级别的列表。修正:删除类体中的 items = [],在 __init__ 内写 self.items = [],让每个对象拥有自己的列表。

With the Dog class from Worked Example 6, after rex.species = "wolf" what do rex.species, pip.species and Dog.species show, and why?使用例题 6 的 Dog 类,执行 rex.species = "wolf" 后,rex.species、pip.species 和 Dog.species 各显示什么?为什么?

rex.species shows wolf; pip.species and Dog.species show Canis familiaris. The assignment created an instance attribute on rex that hides the class attribute for rex only. The class attribute itself was never changed.

rex.species 显示 wolf;pip.species 和 Dog.species 显示 Canis familiaris。该赋值在 rex 上创建了一个实例属性,只对 rex 遮蔽类属性,类属性本身没有被改变。


Methods方法

Learning objectives学习目标
  • Write methods with self and extra parameters, and call them with dot notation.
  • Classify a method as a mutator or an accessor, and say what it should return (check question 2).
  • Write a method that returns True or False to report whether it succeeded, and use that result (Worked Example 8).
  • Write a method that takes another object as an argument and trace the changes to both objects (Worked Example 8).
  • Explain why Account.deposit(y, 10) and y.deposit(10) are the same call (Worked Example 8).
  • 编写带 self 和额外参数的方法,并用点号调用。
  • 把方法归类为修改器或访问器,并说明它应返回什么(自我检测第 2 题)。
  • 编写返回 True 或 False 来报告是否成功的方法,并使用该结果(例题 8)。
  • 编写以另一个对象为实参的方法,并追踪两个对象的变化(例题 8)。
  • 解释为什么 Account.deposit(y, 10) 与 y.deposit(10) 是同一个调用(例题 8)。
Methods = functions that belong to a class: three rules.方法 = 属于类的函数:三条规则。
  • Always have self as first parameter第一个参数始终为 self: def describe(self):. You call it as obj.describe(); Python passes self automatically.:def describe(self):。调用时写 obj.describe(),Python 自动传入 self。
  • Methods can take extra parameters方法可以有额外参数: def deposit(self, amount): takes one extra argument. Call: acc.deposit(100). ICS4C B2.1: "create and use instance methods.":def deposit(self, amount): 额外接收一个参数。调用:acc.deposit(100)。ICS4C B2.1:"创建和使用实例方法。"
  • Methods can return values方法可以返回值: def get_balance(self): return self.balance. This is the accessor (getter) pattern. Methods that change state without returning are mutators (setters).:def get_balance(self): return self.balance。这是访问器(getter)模式。改变状态但不返回值的方法是修改器(setter)。
CSE3120 1.1.3: "use of private, public and protected members, accessors and modifiers to control access to data."CSE3120 1.1.3:"使用私有、公有和受保护成员、访问器和修改器来控制数据访问。"
Worked Example 7: BankAccount with deposit and withdraw methods例题 7:带存款和取款方法的 BankAccount

Extend the BankAccount class with deposit(amount) and withdraw(amount) methods, and a get_balance() accessor.扩展 BankAccount 类,添加 deposit(amount)(存款)和 withdraw(amount)(取款)方法,以及 get_balance() 访问器。

class BankAccount:
    def __init__(self, owner, balance):
        self.owner   = owner
        self.balance = balance

    def deposit(self, amount):       # mutator: changes state
        self.balance += amount

    def withdraw(self, amount):      # mutator: changes state
        if amount <= self.balance:
            self.balance -= amount
        else:
            print("Insufficient funds")

    def get_balance(self):           # accessor: returns data
        return self.balance

acc = BankAccount("Alice", 1000)
acc.deposit(200)
acc.withdraw(50)
print(acc.get_balance())   # 1150
Code notes: deposit and withdraw are mutator methods that change self.balance; get_balance is an accessor method that only reads and returns data. When calling acc.deposit(200), Python automatically passes acc as self and 200 as amount.代码注解:deposit 和 withdraw 是修改器方法(mutator,修改器),改变 self.balance;get_balance 是访问器方法(accessor,访问器),只读取并返回数据。acc.deposit(200) 调用时 Python 自动将 acc 传给 self,200 传给 amount。

The withdraw method has a guard: if amount exceeds balance, it prints a message instead of creating a negative balance. This is encapsulation in action; the object protects its own data integrity.withdraw 方法有一个保护检查:如果取款额超过余额,则打印消息而不产生负余额。这是封装(encapsulation,封装)的实际体现,对象保护自身数据的完整性。

Worked Example 8: A method that uses another object: transfer例题 8:使用另一个对象的方法:transfer

Alice has 300 and Bob has 50. Write withdraw so that it returns True on success and False on failure, then write transfer(other, amount) that moves money only when the withdrawal succeeds. Trace a transfer of 120 and a transfer of 500.Alice 有 300,Bob 有 50。编写 withdraw,成功时返回 True,失败时返回 False;再编写 transfer(other, amount),只在取款成功时才转账。追踪一次 120 的转账和一次 500 的转账。

class Account:
    def __init__(self, owner, balance):
        self.owner   = owner
        self.balance = balance

    def withdraw(self, amount):
        if 0 < amount <= self.balance:
            self.balance -= amount
            return True
        return False

    def deposit(self, amount):
        self.balance += amount

    def transfer(self, other, amount):
        if self.withdraw(amount):       # one method calls another on self
            other.deposit(amount)       # and a method on the other object
            return True
        return False

x = Account("Alice", 300)
y = Account("Bob", 50)

print(x.transfer(y, 120))     # True
print(x.balance, y.balance)   # 180 170
print(x.transfer(y, 500))     # False
print(x.balance, y.balance)   # 180 170  (nothing changed)
print(Account.deposit(y, 10), y.balance)   # None 180

Trace of x.transfer(y, 120): inside the method self is x and other is y. self.withdraw(120) checks 0 < 120 <= 300, so Alice's balance becomes 180 and the call returns True; then y.deposit(120) makes Bob's balance 170. For the transfer of 500, the check 500 <= 180 fails, withdraw returns False, and neither balance changes.x.transfer(y, 120) 的追踪:方法内部 self 是 x,other 是 y。self.withdraw(120) 检查 0 < 120 <= 300,所以 Alice 的余额变为 180,调用返回 True;然后 y.deposit(120) 使 Bob 的余额变为 170。转账 500 时,检查 500 <= 180 不成立,withdraw 返回 False,两个余额都不变。

The last line shows the equivalence from §2: Account.deposit(y, 10) is the same call as y.deposit(10). A mutator that returns nothing gives None, which is what print shows before the new balance 180.最后一行体现了 §2 的等价关系:Account.deposit(y, 10) 与 y.deposit(10) 是同一个调用。不返回任何值的修改器得到 None,这正是 print 在新余额 180 之前显示的内容。

How do you call the deposit method on a BankAccount object named acc to add 300 dollars?如何对名为 acc 的 BankAccount 对象调用 deposit 方法以存入 300 元?
§4 · Q1
deposit(acc, 300)
acc.deposit(300)
BankAccount.deposit(300)
acc.deposit(self, 300)
acc.deposit(300) is the correct dot-notation call. Python automatically passes acc as the self argument; you only supply the extra arguments (300 for amount).acc.deposit(300) 是正确的点号调用。Python 自动将 acc 作为 self 参数传入;你只需提供额外参数(amount 的 300)。
Method calls use dot notation: object.method(args). Python inserts self automatically; never pass it explicitly in the call.方法调用使用点号表示法:对象.方法(参数)。Python 自动插入 self,调用时永远不要手动传入它。
A method that changes an object's attribute without returning a value is called a…改变对象属性且不返回值的方法称为……
§4 · Q2
Mutator (setter)修改器(setter)
Accessor (getter)访问器(getter)
Constructor构造函数
Destructor析构函数
A mutator (setter) modifies the object's state; it changes one or more attributes. An accessor (getter) reads and returns data without changing it. ICS4C B2.1 names both: "constructors, mutators, accessors."修改器(setter)修改对象的状态,改变一个或多个属性。访问器(getter)读取并返回数据而不改变它。ICS4C B2.1 同时命名了这两者:"构造函数、修改器、访问器。"
Mutator = changes state. Accessor = reads state without changing it. Constructor = __init__, sets up the object when created.修改器 = 改变状态。访问器 = 读取状态而不改变它。构造函数 = __init__,在创建时设置对象。
Exam tip考试提示

Command words: write a method, state the return value, trace. A method that must give a result back uses return; print only shows text and gives the caller None. When a question passes one object into another object's method, draw both objects and update each attribute line by line. Common errors: printing instead of returning, forgetting that a mutator returns None, and writing acc.deposit(self, 300) (Python already supplies self).

指令词:编写方法(write a method)、写出返回值(state the return value)、追踪(trace)。需要把结果交还给调用者的方法用 return;print 只显示文本,调用者得到的是 None。当题目把一个对象传给另一个对象的方法时,画出两个对象,逐行更新每个属性。常见错误:用打印代替返回;忘记修改器返回 None;写成 acc.deposit(self, 300)(Python 已经提供了 self)。

Check your understanding自我检测
Using Account from Worked Example 8, let c = Account("Cy", 100) and d = Account("Di", 0). Give ok, c.balance and d.balance after ok = c.transfer(d, 100), and again after a second ok = c.transfer(d, 1).使用例题 8 的 Account,设 c = Account("Cy", 100),d = Account("Di", 0)。写出 ok = c.transfer(d, 100) 之后,以及再执行一次 ok = c.transfer(d, 1) 之后的 ok、c.balance 和 d.balance。

After the first call: True 0 100. After the second call: False 0 100. The first withdrawal takes exactly 100 (allowed because 100 <= 100). The second asks for 1 from a balance of 0, so withdraw returns False and transfer changes nothing.

第一次调用后:True 0 100。第二次调用后:False 0 100。第一次取款恰好 100(因 100 <= 100 而允许)。第二次要从余额 0 中取 1,所以 withdraw 返回 False,transfer 不改变任何东西。

Classify each method as mutator or accessor, and say what it returns: deposit(amount), get_balance(), transfer(other, amount).把每个方法归类为修改器或访问器,并说明它返回什么:deposit(amount)、get_balance()、transfer(other, amount)。

deposit is a mutator and returns None. get_balance is an accessor and returns the balance without changing anything. transfer is a mutator (it changes two objects), and in Worked Example 8 it also returns True or False to report success.

deposit 是修改器,返回 None。get_balance 是访问器,返回余额而不改变任何东西。transfer 是修改器(它改变两个对象),在例题 8 中还返回 True 或 False 来报告是否成功。

A learner writes def deposit(self, amount): balance += amount and calls acc.deposit(5). What error appears, why, and what is the fix?一位学习者写了 def deposit(self, amount): balance += amount,然后调用 acc.deposit(5)。会出现什么错误?为什么?如何修正?

Python raises an UnboundLocalError. Because the method assigns to balance (with +=), Python treats balance as a local variable, and it has no value yet when += reads it. Attributes need the object in front: write self.balance += amount.

Python 引发 UnboundLocalError。因为方法对 balance 赋值(用 +=),Python 把 balance 当作局部变量,+= 读取它时它还没有值。属性前面必须带对象:写成 self.balance += amount。

Going deeper: method chaining and fluent APIs深入:方法链与流式 API

When a mutator returns self, you can chain calls: acc.deposit(100).deposit(50). This is the "fluent interface" pattern used in many Python libraries (e.g. Pandas df.dropna().reset_index()). For ICS4U / CSE3120-level work, understanding that methods can return self is part of the OOP design vocabulary. At the floor level, returning None from mutators (the default when no return statement is present) is perfectly correct and more common.当修改器返回 self 时,可以链式调用:acc.deposit(100).deposit(50)。这是许多 Python 库使用的"流式接口"模式(如 Pandas 的 df.dropna().reset_index())。对于 ICS4U / CSE3120 级别的学习,理解方法可以返回 self 是 OOP 设计词汇的一部分。在基础级别,修改器返回 None(没有 return 语句时的默认值)是完全正确的,也更常见。


Constructors (__init__)构造函数(__init__)

Learning objectives学习目标
  • State when __init__ runs and why it is never called directly.
  • Write a constructor with a default parameter value, and create objects positionally and with a keyword argument (Worked Example 10).
  • Validate arguments in a constructor and raise ValueError when they are invalid (Worked Example 10).
  • Trace the order of events when an object is created, and explain why no object exists if the constructor raises an error (Worked Example 10).
  • Explain the difference between a constructor parameter and the attribute it initialises (check question 3).
  • 说明 __init__ 何时运行,以及为什么永远不直接调用它。
  • 编写带默认参数值的构造函数,并用位置实参和关键字实参创建对象(例题 10)。
  • 在构造函数中验证实参,并在无效时引发 ValueError(例题 10)。
  • 追踪创建对象时事件发生的顺序,并解释构造函数引发错误时为何没有对象产生(例题 10)。
  • 解释构造函数参数与它所初始化的属性之间的区别(自我检测第 3 题)。
__init__ runs automatically every time you create a new object: four key points.__init__ 在每次创建新对象时自动运行:四个要点。
  • Name is always __init__名称始终为 __init__: the double underscores (called "dunder") tell Python this is a special method. Never rename it.:双下划线(称为"dunder")告知 Python 这是特殊方法。永远不要重命名它。
  • Called by ClassName(args)由 类名(参数) 调用: Dog("Fido", 3) calls __init__(self, "Fido", 3) automatically. You never call __init__ directly.:Dog("Fido", 3) 自动调用 __init__(self, "Fido", 3)。永远不要直接调用 __init__。
  • Sets up initial state设置初始状态: its job is to assign starting values to all instance attributes. After __init__ finishes, the object is ready to use.:其任务是为所有实例属性赋初始值。__init__ 完成后,对象即可使用。
  • Can set defaults可以设置默认值: def __init__(self, name, balance=0): makes balance optional. BankAccount("Alice") creates an account with balance 0.:def __init__(self, name, balance=0): 使 balance 可选。BankAccount("Alice") 创建余额为 0 的账户。
Worked Example 9: Rectangle class with constructor and area method例题 9:带构造函数和面积方法的 Rectangle 类

Create a Rectangle class. The constructor takes width and height. Add an area() method and a is_square() method.创建一个 Rectangle(矩形)类。构造函数接受 width(宽)和 height(高)。添加 area()(面积)方法和 is_square()(是否为正方形)方法。

class Rectangle:
    def __init__(self, width, height):
        self.width  = width
        self.height = height

    def area(self):
        return self.width * self.height

    def is_square(self):
        return self.width == self.height

r1 = Rectangle(5, 3)
r2 = Rectangle(4, 4)

print(r1.area())       # 15
print(r1.is_square())  # False
print(r2.area())       # 16
print(r2.is_square())  # True
Code notes: Rectangle(5, 3) triggers __init__(self, 5, 3), setting self.width=5 and self.height=3; r1.area() returns 5 * 3 = 15; r2.is_square() checks 4 == 4, which is True.代码注解:Rectangle(5, 3) 触发 __init__(self, 5, 3),设置 self.width=5、self.height=3;r1.area() 返回 5 * 3 = 15;r2.is_square() 检查 4 == 4 为 True。

Trace through r1 = Rectangle(5, 3): Python calls Rectangle.__init__(r1, 5, 3). Inside: self.width = 5 and self.height = 3. After __init__ returns, r1 is a fully initialised object with both attributes set.追踪 r1 = Rectangle(5, 3):Python 调用 Rectangle.__init__(r1, 5, 3)。内部:self.width = 5 且 self.height = 3。__init__ 返回后,r1 是已完全初始化的对象,两个属性均已设置。

Worked Example 10: Default values and validation in a constructor例题 10:构造函数中的默认值与验证

Write a Wallet class whose balance defaults to 0 and which refuses a negative starting balance. Create a wallet with the default, one with a keyword argument, and one with an invalid balance, and show the order of the messages.编写 Wallet 类,余额默认为 0,并拒绝负的初始余额。分别用默认值、关键字实参和无效余额创建钱包,并展示消息输出的顺序。

class Wallet:
    def __init__(self, owner, balance=0):
        print("init runs for", owner)
        if balance < 0:
            raise ValueError("balance cannot be negative")
        self.owner   = owner
        self.balance = balance

w1 = Wallet("Alice")                # balance uses the default 0
w2 = Wallet("Bob", balance=50)      # keyword argument
print(w1.balance, w2.balance)       # 0 50

try:
    w3 = Wallet("Eve", -5)
except ValueError as e:
    print("Error:", e)

Output, in order: init runs for Alice, init runs for Bob, 0 50, init runs for Eve, Error: balance cannot be negative. Each Wallet(...) call runs __init__ once, at the moment the object is created, before the result is stored in a variable. In Wallet("Eve", -5) the first line of __init__ still prints, then the raise stops the constructor, so no Wallet object is returned and w3 is never assigned.按顺序的输出:init runs for Alice、init runs for Bob、0 50、init runs for Eve、Error: balance cannot be negative。每次 Wallet(...) 调用在对象创建的那一刻运行一次 __init__,然后才把结果存入变量。在 Wallet("Eve", -5) 中,__init__ 的第一行仍会打印,随后 raise 终止构造函数,所以不会返回 Wallet 对象,w3 也从未被赋值。

A default value (balance=0) makes the argument optional; parameters with defaults must come after those without. Validating inside the constructor means an invalid object can never exist, which is encapsulation applied at creation time.默认值(balance=0)使该实参可选;带默认值的参数必须放在没有默认值的参数之后。在构造函数内验证,意味着无效对象永远不可能存在,这是把封装用在创建时刻。

When does Python call __init__?Python 何时调用 __init__?
§5 · Q1
When you delete an object当你删除对象时
When you call any method on the object当你在对象上调用任何方法时
When you import the class当你导入类时
Automatically when a new object is created with ClassName(...)当用 类名(...) 创建新对象时自动调用
__init__ is called automatically every time a new instance is created. Dog("Fido", 3) triggers __init__ to set up the new object's attributes. You never call it directly.__init__ 在每次创建新实例时自动调用。Dog("Fido", 3) 触发 __init__ 设置新对象的属性。你永远不要直接调用它。
__init__ is the constructor; it runs once at object creation. It does not run when you call other methods or delete the object (__del__ is a finalizer that runs when the object is garbage-collected, not a guaranteed destructor).__init__ 是构造函数:在对象创建时运行一次。调用其他方法或删除对象时不会运行(__del__ 是对象被垃圾回收时运行的终结方法,并不保证一定执行)。
Given class Circle: def __init__(self, radius): self.radius = radius, what does c = Circle(7) do?已知 class Circle: def __init__(self, radius): self.radius = radius,c = Circle(7) 做什么?
§5 · Q2
Defines the Circle class with radius 7定义半径为 7 的 Circle 类
Calls the area method on the Circle调用 Circle 的面积方法
Creates a new Circle object with c.radius = 7创建一个 c.radius = 7 的新 Circle 对象
Assigns the integer 7 to the variable c将整数 7 赋给变量 c
Circle(7) creates a new instance. Python calls __init__(self, 7), which runs self.radius = 7. The result is stored in c, so c is a Circle object with c.radius == 7.Circle(7) 创建一个新实例。Python 调用 __init__(self, 7),执行 self.radius = 7。结果存入 c,所以 c 是一个 c.radius == 7 的 Circle 对象。
The class is already defined above. Circle(7) creates a new instance of it, not a new class definition.类已在上方定义。Circle(7) 创建该类的一个新实例,而不是新的类定义。
Exam tip考试提示

Command words: write a constructor, state the output, identify the error. In Python the constructor is always named __init__ (two underscores on each side), not the class name as in Java. Common errors: _init_ with single underscores (it becomes an ordinary method and never runs automatically), a missing self. so the value is lost when the constructor ends, and putting a parameter with a default before one without.

指令词:编写构造函数(write a constructor)、写出输出(state the output)、找出错误(identify the error)。Python 的构造函数总是叫 __init__(两侧各两个下划线),而不是像 Java 那样用类名。常见错误:写成单下划线的 _init_(它变成普通方法,永远不会自动运行);漏写 self. 导致构造函数结束时值丢失;把带默认值的参数放在无默认值的参数之前。

Check your understanding自我检测
A class Circle has def __init__(self, radius=1): self.radius = radius. What are Circle().radius and Circle(7).radius?类 Circle 有 def __init__(self, radius=1): self.radius = radius。Circle().radius 和 Circle(7).radius 各是多少?

1 and 7. With no argument the default radius=1 is used; with Circle(7) the argument replaces the default.

分别是 1 和 7。不给实参时使用默认值 radius=1;Circle(7) 的实参取代默认值。

A class Tag has def __init__(self, label="new") that sets self.label = label and runs print("made", label). What does t1 = Tag(); t2 = Tag("old"); print(t1.label, t2.label) display?类 Tag 有 def __init__(self, label="new"),设置 self.label = label 并执行 print("made", label)。t1 = Tag(); t2 = Tag("old"); print(t1.label, t2.label) 显示什么?

Three lines: made new, made old, then new old. The constructor runs once per object, while each object is created, and the final print runs afterwards.

三行:made new、made old,然后是 new old。构造函数在创建每个对象时各运行一次,最后的 print 在此之后运行。

A learner writes the body of Rectangle.__init__(self, width, height) as width = width; height = height. What happens on Rectangle(2, 3).width, and what is the fix?一位学习者把 Rectangle.__init__(self, width, height) 的函数体写成 width = width; height = height。执行 Rectangle(2, 3).width 会怎样?如何修正?

Python raises an AttributeError: the object has no attribute width. The lines only assign the parameters to themselves (local variables that vanish when the constructor ends). A constructor parameter and the attribute it initialises are different things; the fix is self.width = width and self.height = height.

Python 引发 AttributeError:对象没有属性 width。这两行只是把参数赋给自己(局部变量,构造函数结束时就消失)。构造函数参数与它所初始化的属性是两回事;修正为 self.width = width 和 self.height = height。


Creating and Using Objects创建与使用对象

Learning objectives学习目标
  • Create several objects, store them in a list and loop over them to call methods or read attributes.
  • Compute a total, an average or a maximum over an attribute of a list of objects (Worked Example 11).
  • Pass an object to a function, and explain why a change made inside the function is visible outside it (Worked Example 12).
  • Sort a list of objects with sorted(..., key=lambda ...) and reverse=True (Worked Example 12).
  • Explain why re-binding the parameter inside a function does not change the caller's object (check question 3).
  • 创建多个对象,存入列表,并循环遍历以调用方法或读取属性。
  • 对对象列表的某个属性计算总和、平均值或最大值(例题 11)。
  • 把对象传给函数,并解释为什么函数内所做的修改在函数外可见(例题 12)。
  • 用 sorted(..., key=lambda ...) 和 reverse=True 给对象列表排序(例题 12)。
  • 解释为什么在函数内给参数重新绑定不会改变调用者的对象(自我检测第 3 题)。
The lifecycle of an object: three phases.对象的生命周期:三个阶段。
  • Create (instantiate)创建(实例化): obj = ClassName(args). Calls __init__ automatically. AB CSE3120 2.3.3: "domain analysis" of what objects are needed. ICS4C B2.2: "design a simple base class … using program templates.":obj = 类名(参数)。自动调用 __init__。AB CSE3120 2.3.3:"分析域对象"确定需要哪些对象。ICS4C B2.2:"使用程序模板设计简单基类"。
  • Use (call methods, read/write attributes)使用(调用方法、读/写属性): obj.method() or obj.attribute. Store multiple objects in a list to process them together: students = [s1, s2, s3].:obj.方法() 或 obj.属性。将多个对象存入列表一起处理:students = [s1, s2, s3]。
  • Pass objects to functions将对象传递给函数: objects are first-class values. You can pass a Student to a function, return one from a function, or store a list of them. CSE3120 3.3: "create the classes necessary to instantiate the objects called for by the algorithm.":对象是一等值。你可以将 Student 传给函数、从函数返回,或存储它们的列表。CSE3120 3.3:"创建算法所需的类以实例化对象。"
Worked Example 11: A class roster with multiple Student objects例题 11:包含多个 Student 对象的班级名单

Create five Student objects, store them in a list, and find the class average and the top scorer.创建五个 Student 对象,存入列表,计算班级平均分和最高分学生。

class Student:
    def __init__(self, name, grade):
        self.name  = name
        self.grade = grade

    def is_passing(self):
        return self.grade >= 50

# Create objects and store in a list
roster = [
    Student("Alice",  88),
    Student("Bob",    72),
    Student("Carol",  95),
    Student("David",  61),
    Student("Emma",   45),
]

# Compute class average
total = sum(s.grade for s in roster)
avg   = total / len(roster)
print(f"Class average: {avg:.1f}")   # 72.2

# Find top scorer
top = max(roster, key=lambda s: s.grade)
print(f"Top scorer: {top.name} ({top.grade})")  # Carol (95)

# List failing students
failing = [s.name for s in roster if not s.is_passing()]
print("Failing:", failing)           # ['Emma']
Code notes: sum(s.grade for s in roster) iterates over the object list and accesses each object's grade attribute; max(..., key=lambda s: s.grade) finds the maximum by comparing attributes; s.is_passing() calls an instance method inside a list comprehension.代码注解:sum(s.grade for s in roster) 遍历对象列表并访问每个对象的 grade 属性;max(..., key=lambda s: s.grade) 通过比较属性找最大值;s.is_passing() 在列表推导中调用实例方法。

Key pattern: iterate over a list of objects with a for loop and call methods or read attributes on each one. This is OOP's main productivity advantage over procedural code for managing collections of related data.关键模式:用 for 循环遍历对象列表,对每个对象调用方法或读取属性。对于管理相关数据集合,这是 OOP 相较过程式代码的主要生产力优势。

Worked Example 12: Passing objects to functions and sorting them例题 12:把对象传给函数并排序

Using the five-student roster from Worked Example 11, write a function curve(student, bonus) that adds a bonus to a student's grade (capped at 100), apply it to everyone, then list the students from highest to lowest grade and the students who are still failing.使用例题 11 的五人名单,编写函数 curve(student, bonus),给学生成绩加上加分(上限 100),对每个人使用它,然后按成绩从高到低列出学生,并列出仍不及格的学生。

def curve(student, bonus):
    student.grade = min(100, student.grade + bonus)   # changes the caller's object

for st in roster:
    curve(st, 6)

ranked = sorted(roster, key=lambda s: s.grade, reverse=True)
for st in ranked:
    print(st.name, st.grade)

print([st.name for st in roster if not st.is_passing()])

Output: Carol 100, Alice 94, Bob 78, David 67, Emma 51, then []. The new grades are 88+6, 72+6, 95+6 (capped at 100), 61+6 and 45+6. The function receives a reference to the same Student object that roster holds, so assigning to student.grade changes the object itself and no return is needed. sorted builds a new list and leaves roster in its original order; key=lambda s: s.grade tells it to compare the grades, and reverse=True puts the highest first. Emma now has 51, so nobody fails.输出:Carol 100、Alice 94、Bob 78、David 67、Emma 51,然后是 []。新成绩依次为 88+6、72+6、95+6(上限 100)、61+6 和 45+6。函数收到的是与 roster 中同一个 Student 对象的引用,所以对 student.grade 赋值改变的是对象本身,不需要 return。sorted 构造一个新列表,roster 保持原来的顺序;key=lambda s: s.grade 指定按成绩比较,reverse=True 让最高的排在最前。Emma 现在是 51 分,所以没有人不及格。

You have a list dogs = [Dog("Fido",3), Dog("Bella",5)]. How do you print the name of the first dog?有列表 dogs = [Dog("Fido",3), Dog("Bella",5)]。如何打印第一条狗的名字?
§6 · Q1
print(dogs.name)
print(name[0])
print(dogs[0].name)
print(Dog.name)
dogs[0] retrieves the first object in the list (Fido). Then .name accesses its name attribute. Result: "Fido".dogs[0] 取列表中第一个对象(Fido)。然后 .name 访问其名字属性。结果:"Fido"。
dogs is a list, not an object; it has no .name. You first index into the list to get an object, then use dot notation: dogs[0].name.dogs 是列表,不是对象,它没有 .name。先用索引从列表取对象,再用点号:dogs[0].name。
What does max(roster, key=lambda s: s.grade) return?max(roster, key=lambda s: s.grade) 返回什么?
§6 · Q2
The highest grade value as a number最高成绩的数值
The Student object with the highest grade成绩最高的 Student 对象
The index of the highest-scoring student成绩最高学生的索引
A list of all students sorted by grade按成绩排序的所有学生列表
max(iterable, key=...) returns the element with the maximum key value; here, the Student object whose .grade is largest. To get just the number, you would write max(s.grade for s in roster).max(可迭代对象, key=...) 返回键值最大的元素,这里是 .grade 最大的 Student 对象。若只想要数值,写 max(s.grade for s in roster)。
max(..., key=...) returns the whole object, not the key value. To get the grade number from the result, use .grade on the returned object.max(..., key=...) 返回整个对象,而非键值本身。要从结果获取成绩数值,对返回对象用 .grade。
Exam tip考试提示

Command words: write code to, trace, state the output. Choose the shape first: a loop that calls a method on every object, a generator or comprehension that collects a value, max(..., key=...) for the best object, or sorted(..., key=...) for an order. Common errors: indexing the list in the wrong order (dogs.name instead of dogs[0].name), expecting max with a key to return the number rather than the object, and expecting a function that changes an object's attribute to need a return.

指令词:编写代码(write code to)、追踪(trace)、写出输出(state the output)。先选好结构:对每个对象调用方法的循环、收集某个值的生成器或推导式、用 max(..., key=...) 找最佳对象、用 sorted(..., key=...) 得到顺序。常见错误:索引顺序写错(写成 dogs.name 而不是 dogs[0].name);以为带 key 的 max 返回的是数值而不是对象;以为修改对象属性的函数必须有 return。

Check your understanding自我检测
With the Dog class from Worked Example 1, what does def birthday(d): d.age += 1 followed by rex = Dog("Rex", 4); birthday(rex); print(rex.age) print?使用例题 1 的 Dog 类,def birthday(d): d.age += 1 之后执行 rex = Dog("Rex", 4); birthday(rex); print(rex.age) 打印什么?

It prints 5. The parameter d refers to the same object as rex, so d.age += 1 changes the object and the change is visible outside the function.

打印 5。参数 d 与 rex 指向同一个对象,所以 d.age += 1 改变了对象本身,函数外也能看到这一变化。

Given dogs = [Dog("Fido", 3), Dog("Bella", 5), Dog("Rex", 2)], give [d.name for d in sorted(dogs, key=lambda d: d.age)] and the same with reverse=True.已知 dogs = [Dog("Fido", 3), Dog("Bella", 5), Dog("Rex", 2)],写出 [d.name for d in sorted(dogs, key=lambda d: d.age)] 的结果,以及加上 reverse=True 后的结果。

Ascending by age (2, 3, 5): ['Rex', 'Fido', 'Bella']. With reverse=True: ['Bella', 'Fido', 'Rex']. The list dogs itself is not reordered.

按年龄升序(2、3、5):['Rex', 'Fido', 'Bella']。加上 reverse=True:['Bella', 'Fido', 'Rex']。列表 dogs 本身的顺序不变。

Explain the output of def reset(d): d = Dog("New", 0) followed by rex = Dog("Rex", 4); reset(rex); print(rex.name, rex.age), and contrast it with birthday in question 1.解释 def reset(d): d = Dog("New", 0) 之后执行 rex = Dog("Rex", 4); reset(rex); print(rex.name, rex.age) 的输出,并与第 1 题的 birthday 对比。

It prints Rex 4. Inside reset, the assignment d = Dog(...) re-binds the local name d to a brand-new object; the caller's rex still names the original object, which was never touched. birthday changed an attribute of the object that d referred to (mutation), which is why that change is visible outside.

打印 Rex 4。在 reset 内,赋值 d = Dog(...) 把局部名字 d 重新绑定到一个全新的对象;调用者的 rex 仍指向原来的对象,它根本没有被碰过。birthday 修改的是 d 所指对象的属性(变更),所以这一变化在函数外可见。


Encapsulation and a Peek at Inheritance封装与继承初探

Learning objectives学习目标
  • Apply encapsulation: keep data in an attribute marked with a leading underscore and expose it through methods.
  • Explain that _name is only a convention, and that __name triggers name mangling (the attribute is stored as _Class__name) without making data truly secret (Worked Example 14).
  • Write a subclass with class Child(Parent): and call super().__init__(...) (Worked Examples 13 and 14).
  • Override a method in a subclass and call the parent's version with super() (Worked Example 14).
  • Explain polymorphism by tracing a loop over parent and child objects (Worked Example 14 and check question 3).
  • Use isinstance to test class membership, and say why isinstance(child, Parent) is True but the reverse is False (check question 1).
  • 应用封装:把数据放在以下划线开头的属性中,并通过方法对外提供。
  • 解释 _name 只是惯例,而 __name 会触发名称改写(属性实际存为 _类名__name),并不能让数据真正保密(例题 14)。
  • 用 class Child(Parent): 编写子类,并调用 super().__init__(...)(例题 13 和 14)。
  • 在子类中覆盖方法,并用 super() 调用父类的版本(例题 14)。
  • 通过追踪遍历父类和子类对象的循环来解释多态(例题 14 和自我检测第 3 题)。
  • 用 isinstance 检验类归属,并说明为什么 isinstance(子类对象, 父类) 为 True 而反过来为 False(自我检测第 1 题)。
Encapsulation: bundle data + behaviour, control access.封装:捆绑数据与行为,控制访问。
  • What it is是什么: keeping an object's data private and exposing it only through methods. ICS4U C1.2: "demonstrate the ability to apply data encapsulation in program design (e.g., classes, records, structures)." CSE3120 1.1.2: "encapsulation" as a key feature of OOP.:将对象数据保持私有,仅通过方法暴露。ICS4U C1.2:"展示在程序设计中应用数据封装的能力(如类、记录、结构体)。" CSE3120 1.1.2:"封装"为 OOP 关键特性。
  • Why it matters为何重要: the withdraw method in §4 refused negative balances. Without encapsulation, code outside the class could set acc.balance = -999 directly. Hiding data behind methods prevents invalid states.:§4 中的 withdraw 方法拒绝负余额。没有封装,类外代码可以直接设置 acc.balance = -999。通过方法隐藏数据可防止无效状态。
  • Python convention: prefix with underscorePython 惯例:用下划线前缀: self._balance signals "treat as private, use the getter/setter." Python does not enforce access control the way Java does, but the convention is universal.:self._balance 表示"视为私有,使用 getter/setter"。Python 不像 Java 那样强制访问控制,但这一惯例普遍通用。
Worked Example 13: Encapsulated BankAccount + a peek at inheritance例题 13:封装的 BankAccount + 继承初探

Show encapsulation with a private _balance, then extend BankAccount to create a SavingsAccount subclass with an interest method.用私有 _balance 展示封装,再扩展 BankAccount 创建带利息方法的 SavingsAccount(储蓄账户)子类。

Encapsulation with private attribute.用私有属性实现封装。

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner    = owner
        self._balance = balance      # private by convention

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount

    def withdraw(self, amount):
        if 0 < amount <= self._balance:
            self._balance -= amount

    def get_balance(self):           # accessor: safe read
        return self._balance
Code notes: self._balance prefixed with underscore signals "private." External code should read via get_balance() and modify via deposit()/withdraw(), not by directly accessing acc._balance.代码注解:self._balance 加下划线表示"私有"(private,私有)。外部代码应使用 get_balance() 读取,使用 deposit()/withdraw() 修改,而不是直接访问 acc._balance。

Inheritance: SavingsAccount extends BankAccount.继承:SavingsAccount 继承 BankAccount。

class SavingsAccount(BankAccount):   # inherits BankAccount
    def __init__(self, owner, balance, rate):
        super().__init__(owner, balance)  # call parent __init__
        self.rate = rate              # new attribute

    def add_interest(self):           # new method
        self._balance *= (1 + self.rate)

savings = SavingsAccount("Alice", 1000, 0.05)
savings.deposit(200)          # inherited from BankAccount
savings.add_interest()        # new method
print(savings.get_balance())  # 1260.0
Code notes: class SavingsAccount(BankAccount): declares inheritance; SavingsAccount is the subclass; BankAccount is the superclass. super().__init__(...) calls the parent constructor. savings.deposit(200) uses the deposit method inherited from the parent; no need to rewrite it.代码注解:class SavingsAccount(BankAccount): 声明继承(inheritance,继承),SavingsAccount 是子类(subclass,子类),BankAccount 是父类(superclass,父类)。super().__init__(...) 调用父类构造函数。savings.deposit(200) 使用的是从父类继承来的 deposit 方法,无需重写。

Inheritance says "a SavingsAccount is a BankAccount with extra features." It inherits all methods from the parent and adds new ones. CSE3120 1.1.2 lists "inheritance" as a key OOP feature. ICS4U A2.2 names "inheritance, method overloading, method overriding, polymorphism" as the full picture (a topic for later Java and university OOP courses; not required in the current AP CSA course). This guide stops at one level of inheritance.继承表示"SavingsAccount 是具有额外功能的 BankAccount"。它从父类继承所有方法并添加新方法。CSE3120 1.1.2 将"继承"列为关键 OOP 特性。ICS4U A2.2 命名了"继承、方法重载、方法覆盖、多态"(属于后续 Java 和大学 OOP 课程的内容;当前 AP CSA 课程不要求)。本指南止于一层继承。

Worked Example 14: Overriding a method, super(), polymorphism and name mangling例题 14:覆盖方法、super()、多态与名称改写

Extend BankAccount with a SavingsAccount that keeps a minimum balance of 100 by overriding withdraw. Put one of each in a list and withdraw 450 from both, then test class membership, add interest, and show what a double-underscore attribute really becomes.扩展 BankAccount,增加 SavingsAccount,通过覆盖 withdraw 使其保持 100 的最低余额。把两种账户各放一个到列表中,对两者都取 450,然后检验类归属、计算利息,并展示双下划线属性实际变成了什么。

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner    = owner
        self._balance = balance          # leading underscore: private by convention

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount

    def withdraw(self, amount):
        if 0 < amount <= self._balance:
            self._balance -= amount

    def get_balance(self):
        return self._balance

    def __str__(self):
        return f"{self.owner}: {self._balance}"


class SavingsAccount(BankAccount):
    MIN_BALANCE = 100                    # class attribute shared by all savings accounts

    def __init__(self, owner, balance, rate):
        super().__init__(owner, balance) # let the parent set owner and _balance
        self.rate = rate

    def add_interest(self):
        self._balance += self._balance * self.rate

    def withdraw(self, amount):          # overrides BankAccount.withdraw
        if self._balance - amount >= self.MIN_BALANCE:
            super().withdraw(amount)     # reuse the parent's checks and update

accounts = [BankAccount("Bob", 500), SavingsAccount("Alice", 500, 0.05)]
for acc in accounts:
    acc.withdraw(450)                    # same call, different method runs
    print(acc)
# Bob: 50
# Alice: 500

print(isinstance(accounts[1], BankAccount), isinstance(accounts[0], SavingsAccount))   # True False
print(type(accounts[1]).__name__)        # SavingsAccount

sv = SavingsAccount("Cy", 1000, 0.05)
sv.add_interest()
print(sv.get_balance())                  # 1050.0

class Vault:
    def __init__(self):
        self.__code = 42                 # double underscore: name mangling

v = Vault()
print(hasattr(v, "__code"))              # False
print(v._Vault__code)                    # 42
print(list(vars(v)))                     # ['_Vault__code']

Polymorphism: the loop calls acc.withdraw(450) on both objects, and Python runs the version that belongs to each object's own class. Bob's plain BankAccount allows it (500 becomes 50). Alice's SavingsAccount would drop to 500 - 450 = 50, below MIN_BALANCE 100, so its overriding withdraw refuses and her balance stays 500. When the minimum is respected, the override calls super().withdraw(amount) so the parent's validation and update are reused rather than copied.多态:循环对两个对象都调用 acc.withdraw(450),Python 运行的是各对象自己所属类的那个版本。Bob 的普通 BankAccount 允许取款(500 变为 50)。Alice 的 SavingsAccount 取款后会降到 500 - 450 = 50,低于 MIN_BALANCE 的 100,所以覆盖后的 withdraw 拒绝执行,她的余额保持 500。当满足最低余额时,覆盖方法调用 super().withdraw(amount),复用父类的验证和更新,而不是复制代码。

isinstance(accounts[1], BankAccount) is True because a SavingsAccount is a BankAccount (the is-a relationship), but a plain BankAccount is not a SavingsAccount, so the second test is False. add_interest gives 1000 + 1000 × 0.05 = 1050.0 (a float).isinstance(accounts[1], BankAccount) 为 True,因为 SavingsAccount 是(is-a)BankAccount;但普通的 BankAccount 不是 SavingsAccount,所以第二个检验为 False。add_interest 的结果是 1000 + 1000 × 0.05 = 1050.0(浮点数)。

Name mangling: inside the class, self.__code is stored under the name _Vault__code, so hasattr(v, "__code") is False but v._Vault__code still works. The double underscore prevents accidental clashes with a subclass attribute; it is not a security feature, and a single underscore is the usual way to say "internal, please use the methods".名称改写:在类内部,self.__code 实际存在名字 _Vault__code 之下,所以 hasattr(v, "__code") 为 False,而 v._Vault__code 仍然可以访问。双下划线用来避免与子类属性意外重名,它不是安全机制;表达"内部使用,请通过方法访问"的常用方式是单下划线。

BankAccountBankAccount ownerowner _balance_balance deposit(amount)deposit(amount) withdraw(amount)withdraw(amount) get_balance()get_balance() __str__()__str__() inherits (is-a)继承(is-a) SavingsAccountSavingsAccount MIN_BALANCE = 100MIN_BALANCE = 100 raterate add_interest()add_interest() withdraw(amount)withdraw(amount) overrides parent覆盖父类 class name类名 attributes属性 methods方法
Figure 1. UML class diagram of the two classes in Worked Example 14. Each box has a name, an attributes compartment and a methods compartment. The hollow triangle sits at the parent end of the inheritance arrow, so read the arrow from SavingsAccount (child) up to BankAccount (parent). The child lists only what it adds or overrides: MIN_BALANCE, rate, add_interest() and its own withdraw(amount). owner, _balance, deposit, get_balance and __str__ are inherited.图 1. 例题 14 中两个类的 UML 类图。每个方框有类名、属性区和方法区。空心三角形位于继承箭头的父类一端,所以请从 SavingsAccount(子类)向上读到 BankAccount(父类)。子类只列出它新增或覆盖的内容:MIN_BALANCE、rate、add_interest() 和它自己的 withdraw(amount)。owner、_balance、deposit、get_balance 和 __str__ 是继承来的。
What is the main purpose of encapsulation?封装的主要目的是什么?
§7 · Q1
To protect an object's data from being changed in invalid ways, by controlling access through methods通过方法控制访问,保护对象数据不被以无效方式修改
To make programs run faster使程序运行更快
To allow one class to inherit from another允许一个类继承另一个类
To rename methods in a subclass在子类中重命名方法
Encapsulation bundles data and methods together and controls how the data can be changed. By making _balance private and only allowing changes through deposit()/withdraw(), the class prevents invalid states (like negative balance). ICS4U C1.2 states this explicitly.封装将数据和方法捆绑在一起,并控制数据的修改方式。通过将 _balance 设为私有,只允许通过 deposit()/withdraw() 更改,类可防止无效状态(如负余额)。ICS4U C1.2 明确说明了这一点。
Encapsulation is about data protection and controlled access. Inheritance (allowing one class to extend another) is a separate concept covered in the second half of §7.封装是关于数据保护和受控访问的。继承(允许一个类扩展另一个类)是 §7 后半部分介绍的独立概念。
In class SavingsAccount(BankAccount):, what does BankAccount in parentheses mean?在 class SavingsAccount(BankAccount): 中,括号里的 BankAccount 意味着什么?
§7 · Q2
SavingsAccount is a parameter of BankAccountSavingsAccount 是 BankAccount 的参数
BankAccount will be created inside SavingsAccountBankAccount 将在 SavingsAccount 内部创建
SavingsAccount inherits all attributes and methods from BankAccountSavingsAccount 从 BankAccount 继承所有属性和方法
BankAccount will be renamed to SavingsAccountBankAccount 将被重命名为 SavingsAccount
In Python, class Child(Parent): declares inheritance. SavingsAccount inherits all methods and attributes from BankAccount and can add new ones or override existing ones.在 Python 中,class 子类(父类): 声明继承。SavingsAccount 继承 BankAccount 的所有方法和属性,并可添加新的或覆盖现有的。
The parentheses in a class definition specify the parent class for inheritance: not a function parameter, not an instantiation inside, not a rename.类定义中的括号指定继承的父类,不是函数参数,不是内部实例化,也不是重命名。
Exam tip考试提示

Command words: explain encapsulation, write a subclass, state the output of a polymorphic call. For an explanation, give one concrete sentence: "_balance is private by convention, and withdraw checks the amount before subtracting." Choose inheritance only for an is-a relationship (a SavingsAccount is a BankAccount); use an attribute for has-a (a Car has an Engine). Common errors: forgetting super().__init__(...) (the parent's attributes are then never created), believing a leading underscore enforces privacy, and thinking isinstance(parent_object, Child) is True.

指令词:解释(explain)封装、编写(write)子类、写出多态调用的输出(state the output)。解释时给出一个具体的句子:"_balance 按惯例是私有的,withdraw 在减款前检查金额。"只有 is-a 关系才用继承(SavingsAccount 是 BankAccount);has-a 关系用属性(Car 有一个 Engine)。常见错误:忘记 super().__init__(...)(父类的属性就不会被创建);以为前导下划线能强制保密;以为 isinstance(父类对象, 子类) 为 True。

Check your understanding自我检测
With savings = SavingsAccount("Alice", 1000, 0.05) and bank = BankAccount("Bob", 500), give isinstance(savings, SavingsAccount), isinstance(savings, BankAccount) and isinstance(bank, SavingsAccount).已知 savings = SavingsAccount("Alice", 1000, 0.05) 和 bank = BankAccount("Bob", 500),写出 isinstance(savings, SavingsAccount)、isinstance(savings, BankAccount) 和 isinstance(bank, SavingsAccount)。

True, True, False. A savings account is a SavingsAccount, and because it inherits from BankAccount it is also a BankAccount. A plain BankAccount lacks the extra features of the subclass, so it is not a SavingsAccount.

True、True、False。储蓄账户是 SavingsAccount,又因为继承自 BankAccount,所以也是 BankAccount。普通的 BankAccount 没有子类的额外功能,所以不是 SavingsAccount。

A class Pet sets self.name in its __init__(self, name). A subclass Cat(Pet) has __init__(self, name, lives) that only runs self.lives = lives. After c = Cat("Tom", 9), what do c.lives and c.name do, and what is the fix?类 Pet 在 __init__(self, name) 中设置 self.name。子类 Cat(Pet) 的 __init__(self, name, lives) 只执行 self.lives = lives。执行 c = Cat("Tom", 9) 后,c.lives 和 c.name 会怎样?如何修正?

c.lives is 9, but c.name raises an AttributeError. Defining __init__ in the subclass replaces the parent's constructor, so self.name was never set. Fix: start the subclass constructor with super().__init__(name).

c.lives 是 9,但 c.name 引发 AttributeError。在子类中定义 __init__ 会取代父类的构造函数,所以 self.name 从未被设置。修正:在子类构造函数开头写 super().__init__(name)。

A class Animal has speak(self) returning "..." and intro(self) returning "I say " + self.speak(). A subclass Dog(Animal) overrides only speak to return "Woof". What do Animal().intro() and Dog().intro() return? Which idea does this show?类 Animal 有返回 "..." 的 speak(self),以及返回 "I say " + self.speak() 的 intro(self)。子类 Dog(Animal) 只覆盖 speak,返回 "Woof"。Animal().intro() 和 Dog().intro() 各返回什么?这说明了什么概念?

I say ... and I say Woof. Dog inherits intro unchanged, but inside it self.speak() is looked up on the actual object, so a Dog runs its own overriding speak. This is polymorphism: the same call, intro(), behaves according to the class of the object.

I say ... 和 I say Woof。Dog 原样继承 intro,但其中的 self.speak() 是在实际对象上查找的,所以 Dog 运行的是自己覆盖后的 speak。这就是多态:同一个调用 intro(),行为取决于对象所属的类。

Going deeper: method overriding and polymorphism Honors: ICS4U A2.2 / CSE3130深入:方法覆盖与多态 荣誉:ICS4U A2.2 / CSE3130

ICS4U A2.2 (verbatim) lists "encapsulation, inheritance, method overloading, method overriding, polymorphism" as modular design concepts. Method overriding: a subclass replaces a parent method with its own version. Example: SavingsAccount could override withdraw to refuse if the balance would fall below a minimum. Polymorphism: code that works on the parent type also works on any subclass: a function that takes a BankAccount parameter also accepts a SavingsAccount without changes. CSE3130 (Object-oriented Programming 2) extends this with UML design. Inheritance and polymorphism go beyond the current AP CSA course; you meet them in later Java and university OOP courses.ICS4U A2.2(原文)列出"封装、继承、方法重载、方法覆盖、多态"为模块化设计概念。方法覆盖:子类用自己的版本替换父类方法。示例:SavingsAccount 可以覆盖 withdraw,在余额低于最低额时拒绝取款。多态:适用于父类类型的代码也适用于任何子类,接受 BankAccount 参数的函数无需修改也能接受 SavingsAccount。CSE3130(面向对象编程 2)通过 UML 设计扩展了这些内容。继承与多态超出了当前 AP CSA 课程的范围,会在后续的 Java 和大学 OOP 课程中学到。


Exam Strategy and Common Pitfalls考试策略与常见陷阱

Vocabulary matters词汇很重要
  • Use the correct terms.使用正确术语。 Use these terms by name: class, instance/object, attribute/instance variable, method, constructor, encapsulation, inheritance, subclass. Saying "thing" or "box" is an imprecise answer. CSE3120 outcome 1.1 requires you to "describe the core concepts" by name.请按名称使用以下词汇:类(class)、实例/对象(instance/object)、属性/实例变量(attribute/instance variable)、方法(method)、构造函数(constructor)、封装(encapsulation)、继承(inheritance)、子类(subclass)。说"东西"或"盒子"是不精确的回答。CSE3120 结果 1.1 要求你能按名称"描述核心概念"。
  • Class vs instance distinction.类与实例的区别。 A common error: confusing the class (the blueprint) with an instance (the object). "The Dog class defines what a dog is; fido is an instance of it." Practice this sentence until it is automatic.常见错误:混淆类(蓝图)和实例(对象)。"Dog 类定义狗是什么;fido 是它的一个实例。"练习这句话直到自动说出。
Code reading questions (§2-§6)代码阅读题(§2-§6)
  • Trace object state by hand.手工追踪对象状态。 For "what is obj.attr after these lines?", draw a small table: one column per attribute, one row per line that modifies it. ICS4U and CSE3120 both include "trace/read code to determine output."对于"这几行后 obj.attr 是什么?",画一个小表格:每个属性一列,每行修改它时填一行。ICS4U 和 CSE3120 都包含"追踪/阅读代码确定输出"。
  • Remember self.记住 self。 In Python, every instance method must have self as its first parameter, and every attribute access inside a method must use self.attribute. Forgetting the parameter raises a TypeError when the method is called; forgetting the prefix raises a NameError when you read the name, and when you assign it silently creates a local variable that vanishes when the method ends (the attribute is never set).在 Python 中,每个实例方法必须以 self 为第一个参数,方法内每次属性访问必须用 self.属性。忘记参数会在调用方法时引发 TypeError;读取时忘记前缀会引发 NameError,赋值时忘记前缀则会悄悄创建一个随方法结束而消失的局部变量(属性根本没有被设置)。
OOP design questions (§7)OOP 设计题(§7)
  • Explain encapsulation with a concrete example.用具体例子解释封装。 Do not just define it. Say: "The _balance attribute is private. The withdraw method checks that the amount is valid before subtracting, so external code cannot set a negative balance directly." Two sentences, one concrete example.不要只是定义。要说:"_balance 属性是私有的。withdraw 方法在减款前检查金额是否有效,因此外部代码无法直接设置负余额。"两句话,一个具体例子。
  • Inheritance: is-a relationship.继承:is-a 关系。 A SavingsAccount IS-A BankAccount: use inheritance. A Car HAS-A Engine: use composition (attribute), not inheritance. This distinction is ICS4U/CSE3130 territory.SavingsAccount 是(IS-A)BankAccount:用继承。Car 有(HAS-A)Engine:用组合(属性),而非继承。这一区别属于 ICS4U/CSE3130 范畴。
Answer hygiene作答规范
  • Predict output before running.运行前预测输出。 On exam code questions, write out your predicted output, then check by tracing. If you can predict correctly, you understand the code; if not, trace line-by-line.在考试代码题中,先写出预测输出,再通过追踪检查。能正确预测说明你理解代码;若不能,逐行追踪。
  • Python indentation is structural.Python 缩进是结构性的。 In Python, the body of a method must be indented under def. Attribute assignments inside __init__ must be indented twice (once for the class, once for the method). Indentation errors are a common Python OOP syntax mistake.在 Python 中,方法体必须在 def 下缩进。__init__ 内的属性赋值必须缩进两层(一层属于类,一层属于方法)。缩进错误是常见的 Python OOP 语法错误。

Flashcards闪卡

0 / 14 flipped0 / 14 已翻
Class类(class)
Blueprint/template defining the attributes and methods every object of that type will have. Defined with the class keyword.蓝图/模板,定义该类型每个对象将拥有的属性和方法。用 class 关键字定义。
Object / Instance对象 / 实例(object / instance)
A concrete realisation of a class. Created with ClassName(args). Each instance has its own copy of the attributes.类的具体实现。用 类名(参数) 创建。每个实例拥有自己的属性副本。
Attribute / Instance variable属性 / 实例变量(attribute / instance variable)
Data stored per object. Defined with self.name = value inside __init__. Accessed with object.name.每个对象存储的数据。在 __init__ 内用 self.名称 = 值 定义。用 对象.名称 访问。
Method方法(method)
A function that belongs to a class. Always has self as first parameter. Called with obj.method(args).属于类的函数。始终以 self 为第一个参数。用 对象.方法(参数) 调用。
Constructor: __init__构造函数:__init__(constructor)
Called automatically when a new object is created. Sets initial attribute values. Never call it directly.创建新对象时自动调用,设置初始属性值。永远不要直接调用。
What does self refer to?self 指代什么?(What does self refer to?)
The specific object on which the method was called. Python passes it automatically; never include it when calling the method.调用该方法的具体对象。Python 自动传入;调用方法时永远不要手动传入。
Mutator vs Accessor修改器 vs 访问器(mutator vs accessor)
Mutator (setter): changes an attribute, returns nothing. Accessor (getter): reads and returns an attribute, does not change state. ICS4C B2.1.修改器(setter):改变属性,不返回值。访问器(getter):读取并返回属性,不改变状态。ICS4C B2.1。
Encapsulation封装(encapsulation)
Hiding an object's data (private attributes) and controlling access through methods. Prevents invalid state. ICS4U C1.2; CSE3120 1.1.2.隐藏对象数据(私有属性),通过方法控制访问。防止无效状态。ICS4U C1.2;CSE3120 1.1.2。
Private attribute convention私有属性惯例(private attribute convention)
Prefix with one underscore: self._balance. Signals "treat as private." Python does not enforce this; it is a convention.加单下划线前缀:self._balance。表示"视为私有"。Python 不强制,这是惯例。
Inheritance继承(inheritance)
A subclass extends a parent class: class Child(Parent):. Inherits all parent methods/attributes. Adds new ones or overrides existing ones. CSE3120 1.1.2; ICS4U A2.2.子类扩展父类:class 子类(父类):。继承父类所有方法/属性,可添加新的或覆盖现有的。CSE3120 1.1.2;ICS4U A2.2。
super().__init__(...)super().__init__(...)
Calls the parent class constructor from inside the child __init__. Ensures the parent's attributes are set up before the child adds its own.在子类 __init__ 内调用父类构造函数。确保父类属性在子类添加自己属性之前已设置。
OOP is optional in CSTA / absent from AP CSPOOP 在 CSTA 中可选,AP CSP 中缺席
CSTA 3B-AP-14 Descriptive Statement (verbatim): "Object-oriented programming is optional at this level." AP CSP uses procedures, not classes. OOP depth = AP CSA.CSTA 3B-AP-14 描述性说明(原文):"在此级别,面向对象编程是可选的。" AP CSP 使用过程,不使用类。OOP 深度内容 = AP CSA。
PascalCase for classes类名用 PascalCase(PascalCase for classes)
Python PEP 8 convention: class names use CapWords/PascalCase. E.g. BankAccount, StudentRecord. Functions/variables use snake_case.Python PEP 8 惯例:类名用 CapWords/PascalCase。如 BankAccount、StudentRecord。函数/变量用 snake_case。
Is-a vs Has-a是(is-a)vs 有(has-a)
Is-a → use inheritance. A SavingsAccount IS-A BankAccount. Has-a → use composition (attribute). A Car HAS-A Engine (stored as self.engine = Engine()).是(is-a)→ 用继承。储蓄账户是(is-a)银行账户。有(has-a)→ 用组合(属性)。汽车有(has-a)发动机(存为 self.engine = Engine())。

Practice Quiz综合测验

What is the correct Python syntax to define a class named Animal?定义名为 Animal 的类,正确的 Python 语法是什么?
Q1
class Animal:
def Animal():
Animal = class():
class = Animal:
class Animal: uses the class keyword followed by the class name in PascalCase. The colon ends the header; the body is indented.class Animal: 使用 class 关键字,后跟 PascalCase 类名。冒号结束头部;主体缩进。
def defines functions, not classes. Class syntax: class ClassName:, i.e. keyword, name, colon.def 定义函数,不是类。类语法:class 类名:,即关键字、名称、冒号。
Given:
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
What does d = Dog("Rex", 5) produce?
已知以上 Dog 类,d = Dog("Rex", 5) 产生什么?
Q2
A string "Rex 5"字符串 "Rex 5"
An error: you must pass self explicitly错误:必须显式传入 self
The Dog class definitionDog 类的定义
A Dog object with d.name == "Rex" and d.age == 5一个 Dog 对象,其中 d.name == "Rex" 且 d.age == 5
Dog("Rex", 5) creates a new Dog instance. Python calls __init__(self, "Rex", 5), setting self.name = "Rex" and self.age = 5. The object is stored in d.Dog("Rex", 5) 创建新 Dog 实例。Python 调用 __init__(self, "Rex", 5),设置 self.name = "Rex" 和 self.age = 5。对象存入 d。
Python passes self automatically. The result is a Dog object with both attributes set, not a string or an error.Python 自动传入 self。结果是一个已设置两个属性的 Dog 对象,不是字符串或错误。
You add a bark(self) method that prints "Woof!". How do you call it on the dog d?你添加了一个打印 "Woof!" 的 bark(self) 方法。如何在狗 d 上调用它?
Q3
bark(d)
d.bark()
Dog.bark()
d.bark(self)
d.bark(): dot notation, object first, method name, parentheses. Python passes d as self automatically. You never pass self explicitly in the call.d.bark():点号,对象在前,方法名,括号。Python 自动将 d 作为 self 传入。调用时永远不要显式传入 self。
Method calls use dot notation: object.method(). bark(d) would look for a standalone function named bark.方法调用用点号:对象.方法()。bark(d) 会查找名为 bark 的独立函数。
Which of the following correctly uses encapsulation?以下哪项正确使用了封装?
Q4
Setting acc.balance = -500 directly from outside the class从类外部直接设置 acc.balance = -500
Storing all account data in a global variable将所有账户数据存储在全局变量中
Making balance private (self._balance) and providing deposit() and withdraw() methods that validate input将余额设为私有(self._balance),并提供验证输入的 deposit() 和 withdraw() 方法
Using a function outside the class to modify balance使用类外部的函数修改余额
Encapsulation = private data + controlled access through methods. Making _balance private and requiring callers to use deposit()/withdraw() prevents invalid values from being set. ICS4U C1.2.封装 = 私有数据 + 通过方法控制访问。将 _balance 设为私有并要求调用者使用 deposit()/withdraw(),可防止设置无效值。ICS4U C1.2。
Setting acc.balance = -500 directly bypasses validation; that is the opposite of encapsulation. Encapsulation requires controlling access through methods.直接设置 acc.balance = -500 绕过了验证,这是封装的对立面。封装要求通过方法控制访问。
CSTA 3B-AP-14 says OOP is… 🇺🇸 CSTACSTA 3B-AP-14 说 OOP 是…… 🇺🇸 CSTA
Q5
Optional at Level 3B在 3B 级别是可选的
Required for all students at Level 3A3A 级别所有学生必修
Covered in AP CSP Big Idea 3AP CSP 大概念 3 涵盖
Not mentioned in CSTA at allCSTA 完全未提及
CSTA 3B-AP-14 Descriptive Statement (verbatim): "Object-oriented programming is optional at this level." Level 3B is an elective/specialty track, not required for all students.CSTA 3B-AP-14 描述性说明(原文):"在此级别,面向对象编程是可选的。" 3B 级别是选修/专业轨道,并非所有学生必修。
OOP is optional in CSTA 3B and absent from AP CSP entirely. OOP depth is an AP CSA topic. CSTA 3B is the specialty/elective tier, above the required 3A for all students.OOP 在 CSTA 3B 中可选,在 AP CSP 中完全缺席。OOP 深度内容是 AP CSA 主题。CSTA 3B 是专业/选修层,高于所有学生必修的 3A。
Ontario ICS4U C1.2 (verbatim) requires students to "demonstrate the ability to apply _____ in program design." Fill in the blank.安大略 ICS4U C1.2(原文)要求学生"展示在程序设计中应用 _____ 的能力"。填空。
Q6
algorithmic thinking算法思维
recursion递归
binary search二分搜索
data encapsulation数据封装
ICS4U C1.2 (verbatim): "demonstrate the ability to apply data encapsulation in program design (e.g., classes, records, structures)." This is a direct curriculum citation for encapsulation.ICS4U C1.2(原文):"展示在程序设计中应用数据封装的能力(如类、记录、结构体)。"这是对封装的直接课程引用。
ICS4U C1.2 is specifically about data encapsulation. Recursion, binary search, and algorithmic thinking appear in different expectations.ICS4U C1.2 专门讲数据封装。递归、二分搜索和算法思维出现在不同的期望条目中。
AB CSE3120 description (verbatim) says students move from a "procedural programming approach, in which modularity is handled through subprograms, to an object-oriented approach, in which it is handled through…"AB CSE3120 描述(原文)说学生从"通过子程序处理模块化的过程式编程方式,转向通过 _____ 处理模块化的面向对象方式"。
Q7
functions函数
objects对象
arrays数组
algorithms算法
CSE3120 description (verbatim): "…to an object-oriented approach, in which it is handled through objects." The whole OOP paradigm shift is from subprograms (functions) to objects as the unit of modularity.CSE3120 描述(原文):"……转向通过对象处理模块化的面向对象方式。" OOP 范式转变的核心就是从子程序(函数)转向对象作为模块化单元。
CSE3120 is explicit: the OOP paradigm handles modularity through objects (not functions, arrays, or algorithms).CSE3120 明确指出:OOP 范式通过对象(而非函数、数组或算法)处理模块化。

Readiness Checklist准备就绪清单

Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。

0 / 11 mastered已掌握 0 / 11

What This Feeds Into本单元的去向

OOP is the gateway to the AP CSA course. Everything in this guide (class definition, constructors, attributes, methods, encapsulation) maps directly to AP CSA Unit 3 (Class Creation) in Java. The Python syntax differs but the concepts are identical: class, instance, __init__ (Java: constructor), self.attr (Java: this.field), public/private access. The feeder link below goes directly to the AP CSA Class Creation guide.OOP 是进入 AP CSA 课程的门户。本指南中的所有内容(类的定义、构造函数、属性、方法、封装)直接对应 AP CSA 第 3 单元(Java 类的创建)。Python 语法不同但概念相同:类、实例、__init__(Java:构造函数)、self.attr(Java:this.field)、公有/私有访问。下方衔接链接直接指向 AP CSA 类创建指南。

Next step: AP CSA Unit 3 · Class Creation.下一步:AP CSA Unit 3 · 类的创建。

AP CSA Unit 3 · Class Creation (Java OOP: the Python class concepts here map directly to Java classes, constructors, instance variables, and access modifiers)AP CSA Unit 3 · 类的创建(Java 面向对象:这里的 Python 类概念直接对应 Java 的类、构造函数、实例变量和访问修饰符)

Ontario ICS4U and Alberta CSE3120 students who master this guide are well-prepared for AP CSA Unit 3 (Class Creation). The conceptual vocabulary is the same; only the syntax changes. ICS4U A2.2 names "encapsulation, inheritance, method overloading, method overriding, polymorphism", classes and objects are developed in AP CSA Unit 3 (Class Creation), while inheritance, overriding and polymorphism go beyond the current AP CSA course. CSE3130 (OOP 2) extends further into UML-based design.掌握本指南的安大略 ICS4U 和阿尔伯塔 CSE3120 学生已为 AP CSA 第 3 单元(类的创建)做好充分准备。概念词汇相同,只有语法不同。ICS4U A2.2 命名了"封装、继承、方法重载、方法覆盖、多态",其中类与对象在 AP CSA 第 3 单元(类的创建)中展开,而继承、方法覆盖和多态超出了当前 AP CSA 课程的范围。CSE3130(OOP 2)进一步扩展到基于 UML 的设计。

This is the ladder we coach students up: from these high school foundations into AP and IB, and on to first-year university. If you would rather have a guide for the next step than take it on trust, Dingrui Scholars tutors teach exactly this path in one-on-one sessions and small-group classes. A free assessment is the place to start.这正是我们陪伴学生攀登的阶梯:从这些高中基础,迈入 AP 与 IB,再走向大学一年级。如果你希望在下一步有人引路,而不是凭感觉前行,Dingrui Scholars 的导师正是沿着这条路径,以一对一辅导与小班课授课。欢迎从免费评估开始。

Common Questions常见问题

What is the difference between a class and an object?类和对象有什么区别?

A class is the blueprint or template that defines the attributes and methods shared by all objects of that type, while an object is a concrete instance created from that class. For example, Dog is the class and your specific dog is an object.类是蓝图或模板,定义该类型所有对象共有的属性和方法;对象是由该类创建出来的具体实例。例如,Dog 是类,而你那只具体的狗是对象。

What does __init__ do in a Python class?Python 类中的 __init__ 是做什么的?

__init__ is the constructor, a special method that Python calls automatically when you create a new object. Its job is to assign starting values to all the object's instance attributes, and the double underscores tell Python it is a special method you should never rename.__init__ 是构造方法,一个在你创建新对象时由 Python 自动调用的特殊方法。它的任务是给对象的所有实例属性赋初始值,双下划线告诉 Python 这是一个永远不应改名的特殊方法。

What is encapsulation in object-oriented programming?面向对象编程中的封装是什么?

Encapsulation means keeping an object's data private and exposing it only through methods, so other code interacts with the object through a controlled interface rather than touching its internal state directly. This protects the data and makes programs easier to maintain.封装是指把对象的数据保持为私有,只通过方法对外暴露,使其他代码通过受控的接口与对象交互,而不是直接接触其内部状态。这能保护数据并让程序更易维护。

Syllabus alignment & how to use this guide大纲对照与使用说明

How to use this guide如何使用本指南

OOP is an advanced / optional topic across all four curricula at the high-school foundations level. If you are taking ICS4U (Ontario Grade 12), CSE3120 (Alberta Advanced), or Computer Programming 12 (BC), this guide is core material. If you are on the AP CSA track, this guide is the Python warm-up before the Java class-creation unit. If you are in ICS3U, AP CSP, or CSE1110, OOP is not part of your course; bookmark this for later. All code in this guide is Python. The seven sections build in order: you need §1 (what OOP is) before §2 (defining a class) before §5 (constructors).在所有四个课程体系的高中基础级别,OOP 都是进阶/可选主题。如果你正在学习 ICS4U(安大略 12 年级)、CSE3120(阿尔伯塔进阶)或 Computer Programming 12(BC),本指南是核心内容。如果你在 AP CSA 轨道,本指南是进入 Java 类创建单元之前的 Python 热身。如果你在 ICS3U、AP CSP 或 CSE1110,OOP 不在你的课程范围内,先收藏,待以后使用。本指南中所有代码均为 Python。七个章节按顺序递进:需先掌握 §1(OOP 是什么)再学 §2(定义类),再学 §5(构造函数)。

!
If you are cramming the night before如果你在临阵磨枪

Memorise five things: class = blueprint, object = instance; __init__ is the constructor; self refers to the current object; attributes are per-instance variables; methods are functions inside the class. Read every cram-cheat box. The flashcards cover exam vocabulary cold.背熟五件事:类 = 蓝图,对象 = 实例;__init__ 是构造函数;self 指当前对象;属性是每个实例的变量;方法是类内部的函数。读每个速记框。闪卡涵盖考试词汇的冷知识。

*
If you are going for the top mark如果你目标顶分

Work through every worked example by typing the code yourself and running it. Predict the output before you run it. For §7 (encapsulation), understand why hiding data behind methods is a design benefit, not just what it is. The going-deeper box in §7 introduces inheritance. AP CSA itself stops at class creation (Unit 3), so treat inheritance as a preview.亲手输入并运行每个例题代码。运行前预测输出。对于 §7(封装),理解为什么将数据隐藏在方法后面是设计上的优点,而不仅仅是它是什么。§7 的深入框介绍继承。AP CSA 本身止于类的创建(第 3 单元),所以请把继承当作预习。

Prerequisite note.前置说明。 This guide assumes you can write basic Python functions (def, return, parameters). If you have not yet studied functions, complete the HS CS Functions and Modular Design guide first. AB CSE3120 requires CSE2110 (Procedural Programming 1) as a prerequisite; the same underlying principle.本指南假定你已能编写基本 Python 函数(def、return、参数)。如果尚未学过函数,请先完成 HS CS 函数与模块化设计指南。AB CSE3120 要求 CSE2110(过程式编程 1)作为前置,同样的底层原则。