IS-A and HAS-A
easy 40 minIS-A says that an object is a kind of something and can stand in for it.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
See what is fixed in the class and what can change in the object.
Operations
One edit, all children
The parent's battery changes. Who is hit?
Step 1 of 4
Three kinds
All take the battery from the parent.
Step 1: Three kinds
class Smartphone: battery = 3000class SlabPhone(Smartphone): passclass FoldPhone(Smartphone): passclass BasicPhone(Smartphone): passSmartphone.battery = 4000- Good for
- True kinds, stable parent
- Costs
- Every child follows
- Objects changed by one line
- 3
Before editing a parent, list its children. That list is the size of your change.
In the real world
The same is-a and has-a doing real jobs. Pick one and step through it.
What you are born with, and what you carry.
Step 1 of 4
Born with it
Eye colour comes from the parents.
Step 1: Born with it
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Extending for code
criticalThe child gets every method of the parent, also the harmful ones.
Wrongclass Stack(list): ...Rightclass Stack: def __init__(self): self._items = []A class per combination
majorThe number doubles with each option.
Wrongclass BigBatteryPenPhone(BigBatteryPhone)RightPhone(BigBattery(), pen=Pen())A role as a subclass
criticalAn object cannot change its class when the job ends.
Wrongclass Employee(Person): ...Rightperson.start(EmployeeRole(since=10))Reaching through the part
majorEvery caller now depends on the battery.
Wrongphone.battery.charge()Rightphone.charge()Creating the part inside
minorNobody can choose it or fake it.
Wrongself._battery = StandardBattery()Rightdef __init__(self, battery): self._battery = battery
Interview tips
Say it, then test it
- For life?
- All promises?
- Used as the type?
Find the parts
- Adjectives in class names
- Optional, replaceable, for now
- Two reasons to differ
Where IS-A pays
- At the contracts
- Among kinds of a part
- Never for code alone
In the room
- Name the change that becomes cheap
- Draw all three arrows
- Keep healthy hierarchies