跳转到主要内容
模块 7 · 第 2 课(共 4)课程中的26/36~12 min
模块课程(2/4)

继承

继承允许您创建一个新类(子类) 从现有类(基类)继承属性和方法, 并且可以扩展或覆盖它们。

基本语法

Python
class Animale:
    def __init__(self, nome):
        self.nome = nome

    def saluta(self):
        return f"{self.nome} fa un verso"

class Cane(Animale):       # Cane EREDITA da Animale
    def saluta(self):       # OVERRIDE del metodo
        return f"{self.nome} dice WOOF!"

a = Animale("X")
c = Cane("Fido")
a.saluta()      # 'X fa un verso'
c.saluta()      # 'Fido dice WOOF!'

Cane 从 Animale 继承 __init__ 而不重写它。

super():调用基本方法

当您想要扩展基本方法(而不是完全替换它)时,请使用 super():

Python
class Animale:
    def __init__(self, nome):
        self.nome = nome

class Cane(Animale):
    def __init__(self, nome, razza):
        super().__init__(nome)    # delega alla base
        self.razza = razza

c = Cane("Fido", "Labrador")
c.nome        # 'Fido'
c.razza       # 'Labrador'

isinstance:类型检查

Python
isinstance(c, Cane)        # True
isinstance(c, Animale)     # True (anche la base)
isinstance(c, str)         # False

isinstance(x, BaseClass) 还识别所有子类:这就是 使继承对于多态性有用。

Python
animali = [Cane("Fido", "X"), Animale("Pippo")]
for a in animali:
    print(a.saluta())        # ogni oggetto risponde a suo modo

MRO(方法解析顺序)——概述

当你有多重继承时,Python 决定按什么顺序查找 对于遵循 MRO 的方法,使用 C3 算法计算。对于 95% 的情况下,知道以下内容就足够了:

1.它首先出现在实例中,2.然后在其班级中,3. 然后按声明顺序在基类中。

Python
Cane.__mro__
# (<class 'Cane'>, <class 'Animale'>, <class 'object'>)

object 是 Python 3 中每个类的根。

轮到你了

锻炼#python.m7.l2.e1
尝试:0加载中...

给定 `class Vehicle: def __init__(self,brand): self.brand =brand`,使用 __init__(self,brand,model) 定义 `Car(Vehicle)`,调用 super().__init__ 并存储 self.model。创建 `a = Car('Fiat', '500')` 并评估 `(a.brand, a.model)`。

正在加载编辑器...
显示提示

super().__init__(brand) 然后 self.model = model.

3 次尝试后可用的解决方案

复习练习

锻炼#python.m7.l2.e2
尝试:0加载中...

使用 __init__(self, side) 和返回 side * side 的 area() 定义 `class Shape: def area(self): return 0` 和 `class Square(Shape)`。创建 `q = Square(5)` 并评估元组 `(q.area(), isinstance(q, Shape))`。

正在加载编辑器...
显示提示

自我一面*自我一面。

3 次尝试后可用的解决方案

额外的挑战

锻炼#python.m7.l2.e3
尝试:0加载中...

Create a class `Square` that inherits from the `Rectangle` class (defined below). The constructor of `Square` must take a single parameter `side` and pass it to `super().__init__(side, side)`. Instantiate a square with side `6` in `sq` and evaluate `sq.area()`.

正在加载编辑器...
显示提示

Declare class Square(Rectangle): and call super().__init__(side, side) in the constructor.

3 次尝试后可用的解决方案