Add Focused Behavior with Mixins
Core idea
A mixin is a class designed to add a focused capability to other classes through inheritance. It is a design convention, not special Python syntax. Keep each mixin small and document required attributes and methods. If it wraps an existing operation, use cooperative super() and choose a base order that reaches the intended implementations.
class LabelMixin: def label(self): return self.code.upper()class Parcel(LabelMixin): def __init__(self, code): self.code = codeprint(Parcel("a7").label())LabelMixin expects its host to provide a string code.
Wrap a shared operation
class PrefixMixin: def render(self): return "ID: " + super().render()class Item: def render(self): return "7"class Tagged(PrefixMixin, Item): passprint(Tagged().render())The mixin adds a prefix and delegates to Item.
Observe base order
class PrefixMixin: def render(self): return "ID: " + super().render()class Item: def render(self): return "7"class Tagged(Item, PrefixMixin): passprint(Tagged().render())Item.render is selected first and does not continue the chain.
Common mistake
Avoid unrelated responsibilities and hidden state requirements in a mixin. A method that expects self.code fails if its host provides no such attribute.
Practice
Reuse LabelMixin in a second class with a code attribute; then remove that attribute and observe the failure.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Add mixin capabilities
Check your understanding of mixins.
What is printed?
class UpperMixin: def label(self): return self.code.upper()class Box(UpperMixin): def __init__(self): self.code = "a9"print(Box().label())What is printed?
class WrapMixin: def text(self): return "[" + super().text() + "]"class Base: def text(self): return "x"class Box(WrapMixin, Base): passprint(Box().text())Which exception is raised by this intentionally incomplete host?
class LabelMixin: def label(self): return self.codeclass Box(LabelMixin): passBox().label()What makes a mixin easier to reuse?