跳到主要内容

面向对象编程

大学计算机科学知识点 4

本主题的视频课程 打开视频页面
5:16

面向对象编程

这门课讲的是一个小脚本如何成长为一个其他人可以安全修改的系统。前两个单元构建对象:类、引用和封装的保护墙。接下来的两个单元通过组合、继承和接口将对象连接起来。最后两个单元用异常和测试维持系统的运行。每个类都是它与调用者之间的一份契约。

英文讲解 · 可切换中英文字幕

讲义

English

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.

A blueprint: a class is a template that defines how objects of that type are built
A blueprint: a class is a template that defines how objects of that type are built

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 take self, 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
Object and reference graph
Two names on one object: a and c alias the same Book, b is a second, equal-but-distinct object

How Python finds an attribute. For obj.x, Python looks in this order:

  1. the instance (obj.__dict__);
  2. the class;
  3. 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.copies is $1$;
  • b.copies is $3$ (not changed);
  • c.copies is also $1$, because c is a: 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 self in a method header.
  • Changing a class attribute through an instance, and then wondering why other instances show a different value.
  • Expecting d = c to 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
Interface boundary
Public methods form a wall: every state change passes the checks; the fields behind the wall are private

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.

  1. c.issue() succeeds.
  2. c.issue() again raises ValueError. 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).
  3. c.give_back(): now c._out is False, and c.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 Member is a Person);
  • composition 组合 ("has a": a Library has a Catalog).

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
Class relationship diagram
Two connection kinds: inheritance says is-a (hollow triangle to the base); composition says has-a (filled diamond at the whole)

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}'
Dynamic dispatch sequence
One call, three steps: the variable names the interface, the object carries the runtime type, dispatch picks that type's send

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 isinstance checks. 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.

  • raise throws an exception.
  • try/except catches it by type.
  • finally runs 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
Exception flow
Raise in renew unwinds issue and main until a matching handler; finally runs on the way out, on every path

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:

  1. renew raises, because $28 + 10 > 30$.
  2. except runs: kept = 'handled'.
  3. finally runs: 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 catches KeyboardInterrupt and hides real bugs.
  • except ...: pass. The failure disappears and the state is left half updated.
  • Catching Exception when 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:

  1. arrange 准备: set up the objects;
  2. act 执行: make one call;
  3. 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
Test coverage map
Behaviours down, tests across: each cell is a behaviour a test pins; the empty cell is next to write

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.

词汇
English 中文 拼音
object-oriented programming/ˈɒbdʒekt ˈɔːrɪəntɪd ˈprəʊɡræmɪŋ/ 面向对象程序设计 miàn xiàng duì xiàng chéng xù shè jì
class/klæs/ 类 lèi
object/ˈɒbdʒekt/ 对象 duì xiàng
instance/ˈɪnstəns/ 实例 shí lì
instance attributes/ˈɪnstəns ˈætrɪbjuːts/ 实例属性 shí lì shǔ xìng
Class attributes/klæs ˈætrɪbjuːts/ 类属性 lèi shǔ xìng
reference/ˈrefrəns/ 引用 yǐn yòng
aliases/ˈeɪlɪəsɪz/ 别名 bié míng
equality/iːˈkwɒlɪti/ 相等 xiāng děng
identity/aɪˈdentɪti/ 同一 tóng yī
invariant/ɪnˈveərɪənt/ 不变量 bù biàn liàng
encapsulation/ɪnˌkæpsjʊˈleɪʃn/ 封装 fēng zhuāng
inheritance/ɪnˈherɪtəns/ 继承 jì chéng
composition/ˌkɒmpəˈzɪʃn/ 组合 zǔ hé
fragile base class/ˈfrædʒaɪl beɪs klæs/ 脆弱基类 cuì ruò jī lèi
interface/ˈɪntəfeɪs/ 接口 jiē kǒu
polymorphism/ˈpɒlɪmɔːfɪzəm/ 多态 duō tài
duck typing/dʌk ˈtaɪpɪŋ/ 鸭子类型 yā zi lèi xíng
dynamic dispatch/daɪˈnæmɪk dɪˈspætʃ/ 动态绑定 dòng tài bǎng dìng
substitution/ˌsʌbstɪˈtjuːʃn/ 替换 tì huàn
exceptions/ekˈsepʃnz/ 异常 yì cháng
unit tests/ˈjuːnɪt tests/ 单元测试 dān yuán cè shì
coupling/ˈkʌplɪŋ/ 耦合 ǒu hé
cohesion/kəʊˈhiːʒn/ 内聚 nèi jù
single responsibility principle/ˈsɪŋɡl rɪˌspɒnsəˈbɪlɪti ˈprɪnsɪpl/ 单一职责原则 dān yī zhí zé yuán zé
runtime type/ˈrʌntaɪm taɪp/ 运行时类型 yùn xíng shí lèi xíng
open/closed/ˈəʊpən kləʊzd/ 开闭 kāi bì
arrange/əˈreɪndʒ/ 准备 zhǔn bèi
act/ækt/ 执行 zhí xíng
assert/əˈsɜːt/ 断言 duàn yán

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

登录或创建账户

IGCSE, A-Level & AP