Mixins and traits
medium 50 minA mixin or trait is a small bundle of methods that you add to classes that have nothing else in common.
Video lesson · Chapter 1 of 5
Use one behaviour in three unrelated objects
See it run
Who answers a call, who is asked back, and what happens when one link is missing.
Operations
Who answers?
A call walks through the order until a class has the method.
Step 1 of 5
One object, four classes
The object holds the data. The classes stand in one fixed order.
Step 1: One object, four classes
class EnhancedUser(JsonMixin, LogMixin, User): passuser.to_json()user.greet()print(EnhancedUser.__mro__)- Good for
- One ability, many classes
- Costs
- Readers must know the order
Never guess the order. Print it.
In the real world
The same mixins and traits doing real jobs. Pick one and step through it.
Four classes, four selections. No tree can draw this.
Step 1 of 4
User
| Json | Log | Time | |
|---|---|---|---|
| User | yes | yes | yes |
| Product | |||
| TaxTable | |||
| Session |
All three abilities.
Step 1: User
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Reading the host's fields
criticalAnother bundle adds a field, and this one breaks.
Wrongdef to_json(self): return json.dumps(self.__dict__)Rightdef to_json(self): return json.dumps(self.fields())Calling the base by name
criticalThe layers between are skipped.
Wrongdef save(self, k, v): Store.save(self, k, v)Rightdef save(self, k, v): super().save(k, v)Shared state by accident
criticalA list at class level belongs to all objects of all hosts.
Wrongclass Audited: audit = []Rightclass Audited: def __init__(self, **kw): super().__init__(**kw) self.audit = []Base class first
majorIn Python the base answers before the mixin, and the mixin has no effect.
Wrongclass Page(View, LoginRequired): ...Rightclass Page(LoginRequired, View): ...toJSON that calls stringify on itself
majorJSON.stringify calls toJSON: endless recursion.
WrongtoJSON() { return JSON.stringify(this); }RighttoJSON() { return this.fields(); }A bundle with one host
minorThe reader jumps to another file for nothing.
Wrongclass UserHelperMixin: ... # only User uses itRightclass User: ... # the methods live here
Interview tips
Say the contract
- Requires
- Provides
- Holds no state
Know the order
- Python: left first
- Ruby: last include first
- Scala: right first
- Print it
Settle names openly
- Override in the class
- Prefix shared bundles
- Guard hosts
Know when not
- State: a part
- Run time: a decorator
- More than three: split