Skip to content

继承 and 多态

Extend 类使用继承, override 方法, use super(), and leverage 多态.

你将学到

  • 创建 subclasses 那个 inherit 从 parent 类
  • Override and extend parent 方法使用 super()
  • 理解单个 and 多个继承
  • Use isinstance() and issubclass() for 类型检查
  • Apply 多态通过 duck 输入

概念讲解

Basic Inheritance

A subclass inherits all attributes and methods from its parent (base) class. Define a subclass by passing the parent in parentheses:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} 制作 sound"

class Dog(Animal):       # Dog inherits from Animal
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

Dog and Cat inherit the __init__ method from Animal but override the speak method with their own implementation. This is the core of polymorphism — the same method name behaves differently for different classes.

Using super()

The super() function calls the parent class's method. This is essential when you want to extend rather than replace the parent's behavior:

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)   # call Animal.__init__
        self.breed = breed       # add Dog-specific attribute

rex = Dog("Rex", "Labrador")
print(rex.name)   # Rex (from Animal)
print(rex.breed)  # Labrador (from Dog)

Always call super().__init__() in a subclass constructor to ensure the parent's initialization runs. Without it, parent attributes would not be set.

Method Resolution Order (MRO)

Python supports multiple inheritance — a class can inherit from multiple parents. The MRO determines the order in which parent classes are searched for methods:

class Flying:
    def move(self):
        return "Flying"

class Swimming:
    def move(self):
        return "Swimming"

class Duck(Flying, Swimming):
    pass

d = Duck()
print(d.move())  # Flying — first in MRO
print(Duck.__mro__)  # shows the search order

Python uses the C3 linearization algorithm to compute a consistent MRO. You can inspect it with ClassName.__mro__ or ClassName.mro(). The diamond problem is resolved deterministically.

isinstance and issubclass

rex = Dog("Rex", "Labrador")
print(isinstance(rex, Dog))     # True
print(isinstance(rex, Animal))  # True — Dog is a subclass of Animal
print(issubclass(Dog, Animal))  # True

isinstance() returns 真 for both the class and its parents — this is why it is preferred over 类型(x) == Dog for type checks. It respects the inheritance hierarchy.

Polymorphism and Duck Typing

Python uses duck typing: "如果它 walks 如 duck and quacks 如 duck, 它是 duck." You do not need inheritance to get polymorphism — any object with the right method works:

def make_it_speak(thing):
    return thing.speak()  # works with any object that has speak()

class Robot:
    def speak(self):
        return "Beep boop"

make_it_speak(Dog("Rex", "Lab"))  # Rex says Woof!
make_it_speak(Robot())             # Beep boop

The function does not care about the type — it only cares that the object has a speak() method. This is more flexible than strict inheritance-based polymorphism.

Abstract Base Classes

For when you want to enforce that subclasses implement certain methods, use the abc module:

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        import math
        return math.pi * self.r ** 2

# Shape()  # TypeError — cannot instantiate abstract class
c = Circle(5)  # OK — area() is implemented

Abstract base classes define an interface that subclasses must implement. Trying to instantiate a class with unimplemented abstract methods raises TypeError.

示例代码

              # Basic inheritance
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"

    def __str__(self):
        return f"{type(self).__name__}({self.name})"

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Using the classes
rex = Dog("Rex", "Labrador")
whiskers = Cat("Whiskers")
print(rex.speak())       # Rex says Woof!
print(whiskers.speak())  # Whiskers says Meow!
print(rex)               # Dog(Rex)

# isinstance checks
print(isinstance(rex, Dog))     # True
print(isinstance(rex, Animal))  # True
print(issubclass(Cat, Animal))  # True

# Polymorphism — duck typing
def make_it_speak(thing):
    return thing.speak()

class Robot:
    def speak(self):
        return "Beep boop"

for obj in [rex, whiskers, Robot()]:
    print(make_it_speak(obj))

# Abstract base class
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h
    def area(self):
        return self.w * self.h

r = Rectangle(3, 4)
print(f"Rectangle area: {r.area()}")
            

Shows 继承使用 super(), 方法 overriding, isinstance/issubclass, 多态通过 duck 输入 (Robot 使用 speak() 工作 alongside animals), and 抽象基础类 使用 @abstractmethod.

动手试一试

  • JSON Formatter

    对象使用继承 hierarchies 经常 serialize 到 JSON.

  • 情况 Converter

    类 naming 约定 — PascalCase for 类, snake_case for 方法.

常见错误

错误写法

Forgetting 到 call super().__init__() in subclass constructor

正确做法

如果 subclass 定义 __init__, 它必须 call super().__init__(...) 到 initialize parent attributes. 不使用它, parent attributes 是不 设置, leading 到 AttributeError 当 accessing 它们.

错误写法

Using 类型(x) == MyClass 相反的 isinstance(x, MyClass)

正确做法

类型() 做不 respect 继承 — 类型(rex) == Animal 是假 偶数 for Dog. 总是 use isinstance() for 类型检查; 它返回真 for 类 and 所有 parent 类.

相关速查表

练习 继承 and 多态

2 个练习

练习 继承 and 多态

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误