Mixins for shared behaviour

Intermediate Python OOP Inheritance
Created by Pavel · 07.03.2026 at 19:57 UTC · 3 completed

A mixin is a small class that is not meant to stand alone; you merge it into a richer type so several unrelated classes can share the same logging, serialization, or audit hook without duplicating code.

The pattern assumes the host class already defines the attributes the mixin touches—here self.name comes from Entity. If you mixin order is wrong or the attribute is missing, you get runtime errors that look like “mixin bugs” but are really contract bugs.

University approvals: 0
Tasks
Question 1

What is the typical purpose of a mixin?

Hint

Code sharing without deep hierarchy

Question 2

Script: Entity with __init__(self, name) setting self.name. LoggableMixin with log_action(self, action) printing f"{self.name} performed {action}".
class Player(Entity, LoggableMixin): pass
p = Player("hero") then p.log_action("attack").

Expected stdout: hero performed attack (single line).

Hint

Mixin method uses self.name from Entity.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Python OOP Inheritance
  • Difficulty: Intermediate
  • Completed: 3 users
Creator
Pavel
Pavel