IS-A and HAS-A
easy 40 minIS-A says that an object is a kind of something and can stand in for it.
Watch lesson4:45
Implementation
Contract, whole, swap, and a fake part as the proof.
The point: the whole keeps one reference behind a private field, and forwards only what its own users need.
A phone with parts
A contract, and two kinds that keep it.
from __future__ import annotationsfrom typing import Protocolclass Battery(Protocol): @property def capacity(self) -> int: ... def charge(self) -> str: ...class StandardBattery: capacity = 3000 def charge(self) -> str: return "standard charging"class FastChargeBattery: capacity = 5000 def charge(self) -> str: return "fast charging"Lines 5 to 9
What the phone needs from any battery: a number and one action. Without this contract the phone would name a concrete class and could hold no other.
1 of 3
Why it is built this way
- IS-A is used for the parts, where it is true: a fast battery is a battery for its whole life.
Verify
| Step | Expected |
|---|---|
New phone, info() | FlexPhone, 3000 mAh |
swap_battery(fast) returns | The standard battery |
info() again | FlexPhone, 5000 mAh |
| Two phones, one swap | The other phone is unchanged |
Fake battery, one charge() | Counter is 1 |