← 中文资源

简体中文版本

super 沿 MRO 链穿过 mixin

super() 调用的是 C3 线性化里的下一个类而不是固定父类:基类声明顺序决定链的方向,两个父类顺序要求相反时类定义直接抛 TypeError。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

mro: ['Worker', 'TimestampMixin', 'RetryMixin', 'Base', 'object']
call: ['Worker', 'Timestamp', 'Retry', 'Base']
reordered mro: ['ReorderedWorker', 'RetryMixin', 'TimestampMixin', 'Base', 'object']
reordered call: ['Worker', 'Retry', 'Timestamp', 'Base']
inconsistent mro rejected: TypeError

实现说明

super 沿 MRO 链穿过 mixin以类 Base、TimestampMixin、RetryMixin和函数 describe为骨架。 返回值是全新构造的——入参不会被交回去。

使用要点

  • 演示输出是带标签的(mro:、call:、reordered mro:),每个操作都会留下自己的一行标注。
  • 调用方只需要 describe——其余都是内部实现。

常见问题

describe 会修改传入的参数吗?

入参保持不变;拿回来的是新建的值。

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 describe。

主签名形如 def describe(self)

核心语句

except TypeError as exc:
    print("inconsistent mro rejected:", type(exc).__name__)
def describe(self):
    return ["Base"]
def describe(self):
    # super() 在这里不是"父类",而是 MRO 里的下一个类
    return ["Timestamp"] + super().describe()

代码示例

# C3 线性化决定查找顺序:__mro__ 就是 super() 实际走的路径
class Base:
    def describe(self):
        return ["Base"]


class TimestampMixin:
    def describe(self):
        # super() 在这里不是"父类",而是 MRO 里的下一个类
        return ["Timestamp"] + super().describe()


class RetryMixin:
    def describe(self):
        return ["Retry"] + super().describe()


class Worker(TimestampMixin, RetryMixin, Base):
    def describe(self):
        return ["Worker"] + super().describe()


print("mro:", [cls.__name__ for cls in Worker.__mro__])
print("call:", Worker().describe())

# 声明顺序决定 MRO:换一下基类顺序,链的方向随之改变
class ReorderedWorker(RetryMixin, TimestampMixin, Base):
    def describe(self):
        return ["Worker"] + super().describe()


print("reordered mro:", [cls.__name__ for cls in ReorderedWorker.__mro__])
print("reordered call:", ReorderedWorker().describe())

# 两个父类对同一组基类的顺序要求相反时,C3 无法线性化
class First(TimestampMixin, RetryMixin):
    pass


class Second(RetryMixin, TimestampMixin):
    pass


try:
    class Conflict(First, Second):
        pass
except TypeError as exc:
    print("inconsistent mro rejected:", type(exc).__name__)