Python笔记之MRO 与 super()

我的图片 · 在线免费的图片处理工具

前言

简单记录一下Python中的MRO和super()相关的知识点,记录于此,方便自己回顾。

正文

什么是MRO

MRO 的全称是 Method Resolution Order(方法解析顺序)。

Python 在每一个类被定义时,就写好了一张顺序表,写着"以后找方法时,按什么顺序翻"。这张表存在类的 __mro__ 属性里。

class Creature:
    def move(self):
        print("生物移动")
​
class Dog(Creature):
    pass
​
print(Dog.__mro__)
# (<class '__main__.Dog'>, <class '__main__.Creature'>, <class 'object'>)

那 d.move() 发生的时候,Python 到底怎么干活?它老老实实按这张表挨个翻:

步骤去哪翻有没有 move动作
①Dog没有(pass)继续
②Creature有!调用它,打印"生物移动",停

顺序是:Dog → Creature → object。

靠前的父类优先级更高

继承列表 class Dog(Flyable, Swimmable) 里谁写前面,谁就排在 MRO 前面:

class Creature:
    def move(self):
        print("生物移动")
​
class Flyable(Creature):
    def move(self):
        print("飞")
​
class Swimmable(Creature):
    def move(self):
        print("游")
​
class Dog(Flyable, Swimmable):     # Flyable 写在前面
    pass
​
print(Dog.__mro__)
# Dog → Flyable → Swimmable → Creature → object
​
Dog().move()    # 输出:飞   ← Flyable 排在前面,先被找到

把顺序换一下:

class Dog(Swimmable, Flyable):     # Swimmable 写在前面
    pass
​
print(Dog.__mro__)
# Dog → Swimmable → Flyable → Creature → object
​
Dog().move()    # 输出:游   ← Swimmable 排到前面了

注意: 括号里靠前的父类优先级高,它的同名方法会把后面的盖住。 Creature 始终稳稳排在表的最末尾(除了 object)——它永远是那个兜底的爷爷辈。

父类里没有这个方法?跳过,继续找

如果父类只有一个move()呢?

class Eater:                         # 一个"空"类:只负责占个位,什么方法都不写
    pass
​
class Creature:
    def speak(self):
        print("动物叫")
​
class Dog(Eater, Creature):           # Eater 在前,但它没有 speak
    pass
​
Dog().speak()     # 输出:动物叫
​
print(Dog.__mro__)
# Dog → Eater → Creature → object

查找过程:

步骤去哪翻有没有 speak动作
①Dog没有继续
②Eater没有继续
③Creature有!调用,打印"动物叫"

Eater 里没有 speak,只是被"翻了一下"就跳过了。链条不会断,也不会报错。

super()

继承关系一旦复杂,光看括号顺序就不够了

下面对比两个版本进行验证

版本 A:Swimmable 不继承 Creature

class Creature:                       # 老祖宗,提供最基础的 move
    def move(self):
        print("生物移动")
​
class Swimmable:                      # ← 没有 (Creature),和 Creature 谁都不认识谁
    def move(self):
        print("游")
        super().move()                # 这一行的命运,看下方输出
​
class Flyable(Creature):
    def move(self):
        print("飞")
        super().move()
​
class Dog(Flyable, Swimmable):        # 括号顺序:Flyable 在前
    pass
​
print([c.__name__ for c in Dog.__mro__])
# ['Dog', 'Flyable', 'Creature', 'Swimmable', 'object']
#                       ↑ Creature 跑到 Swimmable 前面了!
​
Dog().move()
# 飞
# 生物移动        ← "游"没打印,Swimmable 被跳过了

版本 B:Swimmable 继承 Creature

class Creature:
    def move(self):
        print("生物移动")
​
class Swimmable(Creature):            # ← 有 (Creature),成了 Creature 的子类
    def move(self):
        print("游")
        super().move()
​
class Flyable(Creature):
    def move(self):
        print("飞")
        super().move()
​
class Dog(Flyable, Swimmable):        # 括号顺序:Flyable 在前
    pass
​
print([c.__name__ for c in Dog.__mro__])
# ['Dog', 'Flyable', 'Swimmable', 'Creature', 'object']
#                       ↑ Swimmable 回到 Creature 前面了
​
Dog().move()
# 飞
# 游
# 生物移动        ← "游"打印出来了
对比项版本 A:Swimmable 不继承 Creature版本 B:Swimmable(Creature)
MRO 后半段Flyable → Creature → SwimmableFlyable → Swimmable → Creature
Dog().move() 输出飞 → 生物移动飞 → 游 → 生物移动
Swimmable.move 执行了吗❌ 被 Creature 盖住了✅ 执行了
Swimmable 里的 super()死代码,根本没跑到正常执行,调到 Creature

为什么顺序会反过来

只因为一条铁律:*子类必须排在父类前面。

  • 版本 A:Swimmable 和 Creature 谁都不认识谁,没有这条约束,所以 Creature 紧跟 Flyable 排到了前面,Swimmable 被挤到了后面。

  • 版本 B:Swimmable 成了 Creature 的子类,它必须排在 Creature 前面,于是回到了 Creature 之前。

铁律:子类必须排在父类前面!

super() 是一次全新的查找

很多人以为 super() 就是"调用父类"。它不是,从其他编程语言过来确实容易误解。

"找到就停"和"super() 接力"一点都不矛盾

class Creature:
    def move(self):
        print("生物移动")
​
class Swimmable(Creature):
    def move(self):
        print("游")
        super().move()
​
class Flyable(Creature):
    def move(self):
        print("飞")
        super().move()
​
class Dog(Flyable, Swimmable):
    def move(self):
        print("狗上场")
        super().move()

输出:

狗上场
飞
游
生物移动

四个类全走了一遍,为什么? 因为这里一共发生了 4 次查找,每一次都老老实实遵守"找到就停":

第几次谁发起从哪开始找停在哪打印
第 1 次d.move()DogDog.move狗上场
第 2 次Dog 里的 super()FlyableFlyable.move飞
第 3 次Flyable 里的 super()SwimmableSwimmable.move游
第 4 次Swimmable 里的 super()CreatureCreature.move生物移动

所以:

  • "找到就停" 说的是每一次查找:第 1 次在 Dog 就停了,第 2 次在 Flyable 停了。

  • "全部走一遍" 是因为每次停下的地方,自己又用 super() 发起了下一次查找。

打个比方: 这不是一个人沿楼梯一直往下走,而是每一层的人干完自己的活,按一下电梯按钮,让电梯把活送到下一层。每层都停,只是每层都会再叫一次电梯。

去掉一个 super(),链条当场就断

把上面代码里的 Flyable 改成这样:

class Flyable(Creature):
    def move(self):
        print("飞")       # 没写 super()

输出只剩:

狗上场
飞

第 2 次查找照样在 Flyable 停下,但这次它没写 super(),于是没有第 3 次。Swimmable 和 Creature 一次都没被翻到。

记住: 谁不写 super(),链条就断在谁那里。这和是不是菱形继承、是不是多继承都没有关系。

super() 找的是"方法名",不是"父类"

这个是重点,知道这个就容易理解本章内容。

class Creature:
    def move(self):
        print("生物移动")
​
class Swimmable(Creature):
    def move(self):
        print("游")
​
class Flyable(Creature):
    def fly(self):            # ← 只有 fly,没有 move
        print("飞")
        super().move()        # ← super() 写在 fly 里,找的却是 move
​
class Dog(Flyable, Swimmable):
    pass
​
d = Dog()
d.fly()
# 飞
# 游

执行过程:

步骤做什么说明
①找 fly,在 Flyable 找到打印"飞"
②fly 里的 super().move()新的一次查找,找的是 move
③从 Flyable 后面找 move在 Swimmable 找到,打印"游"

super() 只认两件事:MRO 里的"下一个类",和那个"方法名"。所以这里调到的是 Swimmable.move,而不是"Flyable 的父类 Creature 的 move"。Creature 的 move 排在 Swimmable 后面,根本轮不到它。

一句话:super() 不是"调父类",而是"按 MRO 从下一个类开始,找那个同名方法"。

菱形继承

第八节讲的其实就是前面一直在用的结构,它有个正式名字——菱形继承(也叫钻石继承):

            Creature
           /        \
    Flyable          Swimmable
           \        /
              Dog

两条线汇到同一个老祖宗 Creature 上。这正是 MRO 算法真正要解决的问题。

如果没有 MRO 规则,会出什么问题

按老算法(Python 2 里经典类的深度优先)查 Dog.move,路径是:

Dog → Flyable → Creature(找到!) → 停     ← Swimmable 被跳过了!

Swimmable 被彻底无视,它重写的 move 永远没机会执行。子类辛辛苦苦重写的方法,被老祖宗给盖了——这是面向对象里最不能接受的事。

MRO 是怎么解决的

Python 的 MRO 算法(C3 算法)只保证了一件事:

每条继承线上的重写,都一定比老祖宗优先被查到。

所以在前面的表里,Swimmable 和 Flyable 都排在 Creature 前面,绝不会出现中间层被跳过的情况。你不需要记住 C3 的公式,只要知道它守住这条底线就够了。

super() 在菱形继承里的真正价值:每个类只执行一次

还是这段代码(和 7.1 完全一样,因为它本来就是菱形):

class Creature:
    def move(self):
        print("生物移动")
​
class Swimmable(Creature):
    def move(self):
        print("游")
        super().move()
​
class Flyable(Creature):
    def move(self):
        print("飞")
        super().move()
​
class Dog(Flyable, Swimmable):
    def move(self):
        print("狗上场")
        super().move()
  • MRO:Dog → Flyable → Swimmable → Creature → object

  • 输出:狗上场 → 飞 → 游 → 生物移动

请注意 Creature.move 只执行了一次。理论上它可以通过 Flyable 和 Swimmable 两条路径被调到,但 MRO 把 Creature 在表里合并成了一个位置,链条只经过它一次。

小结

  1. MRO 是一张顺序表,在 class 定义那一行算好,永远不变;调用和方法里有没有 super() 都改不了它。

  2. 找方法就是按表挨个翻:有这个方法就调用并停下,没有就跳过看下一个。

  3. super() 是一次新的查找,从表里"下一个类"开始,找那个同名方法——它只认表和名字,不认"父类"。

MRO = 火车编组(印好就不变):

[Dog] ──► [Flyable] ──► [Swimmable] ──► [Creature] ──► [object]

super() = 车门:

Dog.move ──开门──► Flyable.move ──开门──► Swimmable.move ──开门──► Creature.move

每层都"找到就停",只是每层都会再开一次门。没门(没写 super()),就停在这一层。

概念什么时候确定会不会变作用
MRO 顺序表class 定义那一行永远不变规定"先翻谁后翻谁"
super()方法被调用时执行每次按表往下走一格发起下一次查找
方法有没有被找到查找过程中找到就停决定这次调用执行了谁

参考文章

  1. AI

  2. Python文档

暂无评论

none
暂无评论...