super Follows The MRO Chain Across Mixins
super() calls the next class in the C3 linearization rather than a fixed parent: mixin order decides the chain and conflicting orders fail at definition.
Code
# 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__)Output
Captured from a sandboxed run of this snippet in the build pipeline.
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: TypeErrorWhat the code does
The working surface is the classes Base, TimestampMixin and RetryMixin and the function describe — everything else is wiring.
It builds and returns a fresh value rather than reusing its inputs.
Watch out for
- The runtime is the only requirement — no packages, no install.
Applying it
The main signature reads def describe(self)
The file announces its steps in the output: mro:, call:, reordered mro:.
The surface worth importing is describe; the helpers around it are private to the snippet.
Statements that matter
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()
Interactive Tools for This Topic
FAQ
- Does `describe` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `describe` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.