What this course is, and how to use it
This is the fourth course in University Computer Science: object-oriented programming 面向对象程序设计. It shows how to grow a small script into a system that other people can change safely: objects that own their state, interfaces that hide how they work inside, and tests that protect behaviour while you change the structure.
A limit, stated once: this is a study course, not a degree. Python 3 is the language used. Every program fragment is original and complete in itself, and was run to produce the outputs shown.
- Units 4.1–4.2 build the object: classes, references and the wall around private state.
- Units 4.3–4.4 connect objects to each other.
- Units 4.5–4.6 keep the system working as it changes.
The habit to build: every class makes a promise to the code that uses it. Each unit names that promise, and every example is a program you can run.
Objects and classes
Why it matters. Programs go wrong when state is spread everywhere. A class 类 keeps state and behaviour together, so there is exactly one place to look. From here on, every system you build is classes calling each other.

The idea.
- A class is a blueprint. An instance 实例 (an object 对象) is one thing built from it.
__init__runs when the object is created and sets the instance attributes 实例属性. Methods takeself, which is the instance itself.- Class attributes 类属性 belong to the class and are shared by all instances.
- Assignment never copies. A variable is a reference 引用 to an object, so two names can be aliases 别名 of one object.
class Book:
next_id = 1 # class attribute, shared
def __init__(self, title, copies):
self.id = Book.next_id; Book.next_id += 1
self.title = title
self.copies = copies # instance attribute
def take(self):
self.copies -= 1; return self.copies

How Python finds an attribute. For obj.x, Python looks in this
order:
- the instance (
obj.__dict__); - the class;
- the base classes.
This one rule explains a classic trap. The assignment obj.next_id = 9
does not change the class: it creates an instance attribute that hides
the class attribute, for that one instance only. In Book above, id
is stored on the instance, while next_id stays on the class. So the
books get ids 1, 2, 3, … and Book.next_id always holds the next free
number.
Worked example 1: tracing one class. With Book above:
a = Book('Signals', 3)
b = Book('Signals', 3)
c = a
a.take(); a.take()
After this:
a.copiesis $1$;b.copiesis $3$ (not changed);c.copiesis also $1$, becausecisa: one object, two names.
a == b is False (by default, == checks identity) and a is c is
True. Equality 相等 compares values (once you define how), and
identity 同一 (is) checks whether two names refer to the same
object.
Worked example 2: the shared counter. After creating a and b,
Book.next_id, a.next_id and b.next_id all read $3$. The counter
belongs to the class, so everyone sees the same value. If you write
a.next_id = 9, only a reads $9$. The class still says $3$, and the
next book still gets id $3$.
Common mistakes.
- Forgetting
selfin a method header. - Changing a class attribute through an instance, and then wondering why other instances show a different value.
- Expecting
d = cto make a copy. It makes an alias.
Summary. Class = blueprint; instance = one thing built from it. An
instance attribute hides a class attribute of the same name. Assignment
makes aliases, never copies. is checks identity; == checks equality
(as you define it).
Encapsulation
Why it matters. Every class has an invariant 不变量: a statement that is true between method calls. For example: a copy is either on the shelf or out with one borrower, and nothing else. Encapsulation 封装 is how the class keeps that statement true: the state is private, and every change goes through a method that checks it.
The idea. In Python, a name that starts with an underscore
(_copies) means "internal: do not touch". Other code uses the public
methods, which form the interface. Check at the gate: the
constructor and every method that changes state either keep the
invariant true or refuse the change.
class Copy:
def __init__(self, title):
if title == '': raise ValueError('empty title')
self._title = title; self._out = False
def issue(self):
if self._out: raise ValueError('already out')
self._out = True
def give_back(self):
if not self._out: raise ValueError('not out')
self._out = False
def is_out(self): # public reader, no wall breach
return self._out

Why one gate is enough. If every change to _out goes through
issue or give_back, you can prove the invariant (_out is exactly
True or False) by reading just those two short methods. Add one
unchecked line that writes _out and the proof is gone. Then the number
of places to check grows with every caller, and so do the bugs.
Worked example 1: the wall holds.
c.issue()succeeds.c.issue()again raisesValueError. The caller cannot reach an impossible state, and the object is unchanged after the failed call (the check comes first, so nothing needs to be undone).c.give_back(): nowc._outisFalse, andc.issue()works again.
The only possible states are True and False, always.
Worked example 2: the cost of a leak. A teammate in a hurry writes
c._out = 'y'. Nothing stops them, because the underscore is only a
convention. Now is_out() returns 'y', which counts as true in an
if but is not True.
- One caller (
if c.is_out():) treats the copy as out. - Another caller (
if c.is_out() is True:) treats it as available.
Two readers disagree about one object, and no method could ever have
produced that state. Fixing it means checking every reader of _out;
preventing it cost two if statements. That difference is the whole
argument for encapsulation.
Common mistakes.
- Returning an internal list (
return self._loans): callers can then change your private state. Return a copy. - Checking values in the constructor but not in the setter.
- Writing a get/set pair for every field. Offer behaviour
(
available()), not storage.
Summary. The underscore marks intent. Methods check at the gate. One checked path for each change keeps invariants provable. Offer behaviour, not fields.
Composition and inheritance
Why it matters. Objects connect in two ways:
- inheritance 继承 ("is a": a
Memberis aPerson); - composition 组合 ("has a": a
Libraryhas aCatalog).
Choosing the wrong one ties classes together so tightly that a fix in the base class breaks its subclasses. This is the fragile base class 脆弱基类 problem.
The idea. With inheritance, initialisation is chained:
super().__init__(...) runs the base class first. With composition, the
whole object owns its parts and passes calls on to them.
class Person:
def __init__(self, name):
self._name = name
class Member(Person):
def __init__(self, name, card_no):
super().__init__(name) # base first
self._card = card_no; self._loans = 0
def borrow(self):
self._loans += 1; return self._loans

The order of initialisation. Member('Ana', 7) runs
Member.__init__. Its first line is super().__init__('Ana'), so
Person.__init__ finishes before any other line of Member runs. The
order is always base class first. If you leave out the super() call,
self._name does not exist when Member needs it. The program then
fails with a clear AttributeError, instead of going wrong quietly.
Worked example 1: composition passes calls on. A Library has a
catalogue (a list of Copy objects):
class Library:
def __init__(self):
self._shelves = [] # composition
def add(self, copy): self._shelves.append(copy)
def available(self):
return sum(1 for c in self._shelves if not c.is_out())
After adding 5 copies and issuing 2, available() returns $3$. The
library has no borrowing logic of its own: it asks its parts. If you
replace the list with something that behaves like a list (a database
table, for example), Library does not change. The parts change; the
whole keeps its interface.
Worked example 2: the fragile base. A base method Receipt.total()
adds up the items. A subclass overrides it by copying the adding-up
code and then subtracting $10$. Later, the base gains a loyalty line,
and every discount receipt silently misses it, because the copy has
become a separate version. The fix: return super().total() - 10.
Override by calling the base, not by copying it. Use inheritance for
"is a" and composition for everything else.
Common mistakes.
- Inheriting just to reuse two methods. Use composition or a plain function instead.
- Forgetting
super().__init__. - Copying base-class logic into an override: the copy goes out of date.
Summary. "Is a" inherits (and calls super()). "Has a" composes
(and passes calls on). Never copy base logic into an override.
Interfaces and polymorphism
Why it matters. Big systems survive change when callers depend on what a thing does, not on which class it is. An interface 接口 names the behaviour. Polymorphism 多态 means one line of calling code runs many different implementations.
The idea. Python checks types while the program runs: any object
with the right methods fits. This is called duck typing 鸭子类型. To
write the contract down, define a Protocol (or an abc.ABC) that names
the methods.
class Notifier(Protocol):
def send(self, text: str) -> str: ...
class EmailNotify:
def send(self, text): return f'email: {text}'
class SmsNotify:
def send(self, text): return f'sms: {text}'

How the right method is chosen. When n.send('due') runs, the
attribute lookup from unit 4.1 starts at the runtime type 运行时类型:
the object itself, not the type written next to the variable. So one
loop body can call a different send for each element. This is
dynamic dispatch 动态绑定: the call is written once, and the method is
chosen for each object at the moment of the call.
Worked example 1: one loop, three senders. Add a third sender,
QueueNotify, with the same shape, and let
team = [EmailNotify(), SmsNotify(), QueueNotify()]:
for n in team:
print(n.send('loan due'))
This prints three lines: email: loan due, sms: loan due and
queue: loan due. Adding a fourth sender changes no existing line,
because the loop never named the actual classes. This is the
open/closed 开闭 principle: open to new types, closed to editing.
Worked example 2: substitution and its trap. A replacement class
that keeps the contract fits in without anyone noticing. One that
narrows the contract breaks things silently. For example, a
SilentNotify.send that raises an error on an empty string breaks a
caller whose contract said "send never raises". The rule of
substitution 替换 (Liskov): a replacement may accept more inputs,
never fewer, and may promise more, never less.
Common mistakes.
- Long chains of
isinstancechecks. Replace them with a method that each class implements. - An override that adds a condition or drops a promise. The caller cannot tell until something breaks.
Summary. Name the behaviour with a Protocol, and depend on that name. The method is chosen by the runtime type. A replacement must keep the whole contract.
Exceptions and error handling
Why it matters. Errors travel. A function three calls deep often cannot fix a failure, but it must not ignore it. Exceptions 异常 carry the error up to the code that can decide what to do, and run each level's clean-up code on the way.
The idea.
raisethrows an exception.try/exceptcatches it by type.finallyruns on every path, success or failure.
A small custom hierarchy of exception classes lets callers catch exactly what they want: a broad base class, with specific subclasses.
class LoanError(Exception): ...
class RenewalError(LoanError): ...
class LimitError(RenewalError): ...
class Loan:
def __init__(self, days):
self.days = days
def renew(loan, extra):
if loan.days + extra > 30:
raise LimitError(f'{loan.days}+{extra} exceeds 30')
loan.days += extra
return loan.days

Why exceptions, and when to use status values. A return value of
$-1$ is just a normal value. Nothing forces the caller to check it, so
a caller who forgets keeps calculating with nonsense, and the failure
spreads silently. An exception cannot be ignored: it moves up through
the calls one by one (running each finally) until an except matches.
If none matches, the program stops with an error message. Errors that
can be ignored get ignored; errors that cannot be ignored get handled.
- Use a status value for expected results that the caller handles right away (for example, "not found" in a lookup).
- Use an exception for a broken contract, or a failure the caller cannot fix.
Worked example 1: a precise catch. renew(Loan(20), 15) raises
LimitError with the message 20+15 exceeds 30. The caller catches
RenewalError (a parent class), and the loan still reads $20$: because
the check comes first, a failed call leaves the state unchanged. The
hierarchy works as a filter, and the caller chooses how broad to catch.
Worked example 2: clean-up on both paths. A lock guard:
locked = True
loan = Loan(28)
try:
total = renew(loan, 10) # raises
except RenewalError:
kept = 'handled'
finally:
locked = False
Trace:
renewraises, because $28 + 10 > 30$.exceptruns:kept = 'handled'.finallyruns:locked = False.
Afterwards, locked is False and the loan still reads $28$: the lock
was released on the failing path. On the success path, finally runs in
the same way. Clean-up that must happen belongs in finally (or a
with block), never just after the last statement.
Common mistakes.
- A bare
except:. It also catchesKeyboardInterruptand hides real bugs. except ...: pass. The failure disappears and the state is left half updated.- Catching
Exceptionwhen you meant one specific subclass.
Summary. Raise when a contract is broken; catch where the code can
decide; use finally for clean-up. A small hierarchy allows precise
handling. A failed call must leave the state unchanged.
Testing and design quality
Why it matters. Refactoring means changing the structure without changing the behaviour. It is only safe when the behaviour is fixed in place by tests. Unit tests 单元测试 do that, and good ones test behaviours, not methods.
The idea. One test checks one behaviour, in three steps:
- arrange 准备: set up the objects;
- act 执行: make one call;
- assert 断言: check the result that can be seen from outside.
"Renewing past the limit raises an error" is a behaviour; test_days is
just a method name.
def test_renew_ok():
loan = Loan(20) # arrange
out = renew(loan, 7) # act
assert out == 27 # assert
def test_renew_boundary():
assert renew(Loan(20), 10) == 30 # exactly 30 is allowed
def test_renew_limit():
loan = Loan(20)
try:
renew(loan, 11); assert False
except LimitError:
assert loan.days == 20 # unchanged

Why test behaviours first. A test named after a method breaks every time the method is renamed, but keeps passing when the behaviour changes: lots of noise, no safety. A test named after a behaviour does the opposite. Plan your tests from the list of behaviours: each case in the contract is one row, and the grid shows which test to write next.
Worked example 1: three behaviours, three tests. For renew:
- within the limit: $20 + 7 = 27$;
- exactly at the limit: $20 + 10 = 30$ is allowed, because the check is $> 30$;
- past the limit: $20 + 11$ raises, and the state is unchanged.
The boundary test catches the classic slip of writing >= instead of
>. Running the tests prints 3 passed.
Worked example 2: refactoring while the tests pass. The fine
calculation moves out of Loan into a new FineCalculator class. This
follows the single responsibility principle 单一职责原则: a class
should have one reason to change. The three tests are not touched, and
still print 3 passed. The behaviour stayed the same while the
structure moved: coupling 耦合 (how much classes depend on each other)
went down, and cohesion 内聚 (how well each class's parts belong
together) went up.
Common mistakes.
- Testing private internals. Refactoring then breaks the tests.
- Tests that share changing state (test B passes only after test A has run).
- Chasing line coverage on simple getters while the limit case has no test.
Summary. Arrange, act, assert, one behaviour per test. Tests fix the behaviour so that refactoring is safe. The single responsibility principle lowers the cost of change. Aim for low coupling and high cohesion in every change.