Composición e herencia
Introducido
5:16
Programación orientada a objetos
This course is about how a small script grows into a system that other people can safely change. The first two units build the object: classes, references and…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| classes/ˈklæsɪz/ | |
| inheritance/ɪnˈherɪtəns/ | herencia |
| composition/ˌkɒmpəˈzɪʃn/ | composición |
| base class | |
| fragile base class/ˈfrædʒaɪl beɪs klæs/ | clase base frágil |
| override/ˌəʊvəˈraɪd/ | |
| objects/ˈɒbdʒekts/ | An entity in a program with associated state and behaviour, often an instance of a class. |
One fix, a thousand wrong receipts
- A shop adds a loyalty bonus to its receipt total. The next day every discount receipt is wrong, though nobody touched the discount code.
- The discount class had copied the old total code instead of reusing it. How classes 类 connect decides whether a fix in one place stays a fix everywhere.
Two ways to connect classes
- Inheritance 继承 says is-a: a
Memberis aPerson. Composition 组合 says has-a: aLibraryhas aCatalog. - Inheritance ties classes tightly. When a change to a base class breaks its children, that is the fragile base class 脆弱基类 problem.
super() builds the base first
super().__init__(...)runs the base class's 基类 set-up first, soPerson.__init__finishes before anyMemberline runs. Skip it andself._namedoes not exist whenMemberneeds it.
class Member(Person):
def __init__(self, name, card):
super().__init__(name)
self._card = card
self._loans = 0
Member.init comienza con super().init(name) para que —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
La cadena es de base a primera: omitir super() y self._name no existe aún cuando Member lo necesita.
Ordena los pasos de Member('Ana', 7).
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
La clase base se construye siempre primero, por lo que Member puede confiar en _name.
Override by delegating
- To change a base method, call it and adjust the result:
return super().total() - 10. The base's loyalty bonus then stays in your total. - Copying the base's code into the override 重写 makes a fork. The day the base gains a line, the copy goes stale: that was the receipt bug.
class Receipt:
def total(self):
# the new loyalty line
t = sum(self.prices)
return t - self.bonus()
# Bug: copied, so no bonus
class DiscountReceipt(Receipt):
def total(self):
return sum(self.prices) - 10
# Fix: delegate to the base
class DiscountReceipt(Receipt):
def total(self):
return super().total() - 10
Una sobrescritura que copia el cuerpo del método base —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
El código copiado es una bifurcación: la base sigue cambiando mientras la copia permanece estática.
Receipt.total() devolvió 100. La base luego gana una línea de lealtad que suma 5. DiscountReceipt.total() se escribe como super().total() − 10. ¿Qué devuelve ahora?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
La base ahora proporciona 95, y la sobrescritura resta 10 a eso. Un cuerpo copiado aún diría 90.
Composition delegates
- A
Libraryholds itsCopyobjects 对象 and passes questions on:available()asks each partnot c.is_out()and counts the answers. - The library holds no borrowing logic of its own. Each part keeps its own rules.

Library y su Catalog están mejor conectados mediante —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Has-a es composición: el todo posee partes y reenvía llamadas; cambia la parte, mantén la interfaz.
Swap the part, keep the whole
- Replace the list of copies with a database-backed collection and
Librarydoes not change: parts change, the whole keeps its interface. - Rule of thumb: inheritance 继承 for a true is-a, composition for everything else.
Una clase Library debería heredar de list para poder almacenar sus copias.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Una biblioteca tiene copias; no es una lista. La composición mantiene la lista intercambiable y oculta los métodos de lista que la biblioteca no debería ofrecer.
Worked example: building and counting
Member('Ana', 7)startsMember.__init__, which callsPerson.__init__('Ana')to set_name; then_card = 7and_loans = 0. Twoborrow()calls make_loans2.- A library gets 5 copies and 2 are issued:
available()asks all 5 and returns 3.
Una biblioteca tiene 8 copias. Se prestan 3, luego se devuelve 1 de esas. ¿Qué devuelve available()?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Quedan 2 copias prestadas, por lo tanto 8 − 2 = 6 están disponibles.
Three common slips
- Inheriting just to reuse two methods. Use composition 组合 or a plain function.
- Forgetting
super().__init__. The base's attributes then never exist. - Copying base code into an override. The fork goes stale; delegate with
super().
Recap
| Inheritance 继承 | Composition | |
|---|---|---|
| Says | is-a: a Member is a Person |
has-a: a Library has a Catalog |
| Ties classes | tightly | loosely |
| Rule | call super() so the base is built first |
delegate questions to the parts |
- Override by calling the base, never by copying it.
¿Qué salió mal? Solo el equipo del sitio ve esta información.