Inheritance & encapsulation · 继承与封装
Build on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
在已有的类上扩展
- 继承(inheritance)让一个新类复用一个已有的类。
- 新类是子类(subclass);原来的类是父类(superclass)。
- 写
class Bird(Animal):——Bird会获得Animal的所有方法。(考试伪代码里写作CLASS Bird INHERITS Animal。)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
用 super() 调用父类
- 子类可以在
__init__里添加自己的属性。 - 用
super().__init__(...)先运行父类的__init__。 - 这样就不必重复父类的初始化代码。
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
重写方法
- 子类可以重写(override)方法:定义一个同名的方法。
- 这时会使用子类的版本,而不是父类的。
- 这让每个类都能有自己的行为方式。
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
封装
- 封装(encapsulation)就是把对象的数据安全地保存在它内部。
- Python 没有真正的"私有",但名字前加下划线(
self._balance)表示"外部不要直接动它"。 - 其他代码应通过方法来读取或修改数据,而不是直接伸手进去。
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
多态
- 多态(polymorphism)指同一个方法名,在不同类里有不同的行为。
- 一个循环可以对许多对象调用
.speak(),而无需知道它们的确切类型。 - 每个对象都会以自己的方式做出响应。
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Common mistakes
- A subclass inherits from its parent and can add or override methods.
- Keep data private and reach it through methods (encapsulation).
常见错误
- 子类继承父类,可以新增或重写方法。
- 让数据保持私有,通过方法访问(封装)。
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
现在轮到你
- 运用继承、重写、封装,以及对不同对象调用方法。
- 按检查答案来测试你的代码。
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.) · 已给出类 Animal。编写一个子类 Cat(Animal),从它继承,并添加一个方法 speak(self),返回 "Meow"。(它应仍然拥有继承来的 name_is。)
Click Run to see the output here. · 点击“运行”查看此处输出。
The class Shape is given (its area returns · 返回值 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side. · 已给出类 Shape(它的 area 返回 0)。编写 Square(Shape):它的 __init__(self, side) 应调用 super().__init__("square"),存下 side,并重写 area,使其返回 side * side。
Click Run to see the output here. · 点击“运行”查看此处输出。
Classes Dog and Cat are given, each with a speak(). Write speak_all(animals) that returns · 返回值 a list of each animal's speak() result, in order. · 已给出类 Dog 和 Cat,各有一个 speak()。编写 speak_all(animals),返回一个列表,按顺序装入每个动物 speak() 的结果。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a class Account whose __init__(self) sets a private balance · 平衡 self._balance to · 到 0. Add deposit(self, amount) to add to it, and balance(self) to · 到 return · 回报 it. Other code should use these methods, not touch _balance directly. · 编写一个类 Account,它的 __init__(self) 把一个私有余额 self._balance 设为 0。再添加 deposit(self, amount) 往里存钱,以及 balance(self) 返回余额。其他代码应当使用这些方法,而不是直接去碰 _balance。
Click Run to see the output here. · 点击“运行”查看此处输出。