Skip to content

Inheritance & encapsulation

Python for A-Level CS Lesson 11 2:18 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Inheritance lets a new class start from an existing one instead of from nothing. 继承让一个新类从一个已有的类出发,而不是从零开始。
Animal knows how to describe itself. Animal 知道怎么描述自己。
Now two classes built on it: Bird and Cow. 现在有两个类建立在它之上:Bird 和 Cow。
Neither of them wrote describe — they have it because Animal has it, which is what the violet is telling you. 它们谁都没有写 describe—— 它们有这个方法,是因为 Animal 有,这就是紫色在告诉你的事。
Each then adds its own. 然后各自再加上自己的方法。
And the exam writes the same relationship as CLASS Bird INHERITS Animal. 而考卷把同样的关系写成 CLASS Bird INHERITS Animal。
A subclass usually wants its own data too, and that is where super comes in. 子类通常也想要自己的数据,super 就是用在这里的。
Bird's init takes a name and a wingspan. Bird 的 init 接收一个 name 和一个 wingspan。
It calls super dot init with the name, which runs Animal's setup, and then stores the wingspan itself. 它用 name 调用 super().__init__, 这会运行 Animal 的初始化,然后它自己再存下 wingspan。
The result is one object with both attributes on it — and the colours say which class put each one there. 结果是一个对象上同时有两个属性—— 而颜色告诉你每一个是哪个类放上去的。
A subclass can also override: define a method with the same name, and its version is the one that runs. 子类也可以"覆盖":定义一个同名的方法,运行的就是它的版本。
Duck and Cow both have speak, and they say different things. Duck 和 Cow 都有 speak,而它们说的话不一样。
Now the same call, twice, inside a loop — and you get two different answers. 现在在一个循环里做同样的调用两次—— 你会得到两个不同的答案。
That is polymorphism: one method name, and each object answers for itself. 这就是多态:一个方法名,每个对象各自作答。
The loop never had to ask what type anything was. 这个循环从来不需要问任何东西是什么类型。
Encapsulation is the fourth word, and it is about keeping an object's data safe inside it. 封装是第四个词,讲的是把一个对象的数据安全地留在它内部。
An account holds a balance. 一个账户持有余额。
Reaching straight in and setting it to nine hundred and ninety-nine skips every check the class would have made. 直接伸手进去把它设成 999, 会跳过这个类本来会做的每一项检查。
So the class offers a method instead, and outside code should go through a method to deposit. 所以这个类改为提供一个方法, 外部代码应该通过方法来存钱。
In Python the leading underscore is a signal, not a lock — the language will let you break the rule, and you still should not. 在 Python 里,开头的下划线是一个信号,不是一把锁—— 语言会允许你破坏这条规则,而你依然不应该那么做。
Four things to take with you. 带走四点。
One: a subclass inherits every method the parent has. 第一:子类继承父类的每一个方法。
Two: super runs the parent's init so you do not repeat it. 第二:super 运行父类的 init,这样你不用重复写。
Three: overriding replaces one method, and the rest still come down unchanged. 第三:覆盖只替换一个方法,其余的仍然原样继承下来。
Four: keep data behind an underscore and reach it through methods. 第四:把数据放在下划线后面,并通过方法去访问它。
Now do the three tasks. 现在去做那三道题。

Log in or create account

IGCSE, A-Level & AP