AlgoViz

IS-A and HAS-A

easy 40 min

IS-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

StepExpected
New phone, info()FlexPhone, 3000 mAh
swap_battery(fast) returnsThe standard battery
info() againFlexPhone, 5000 mAh
Two phones, one swapThe other phone is unchanged
Fake battery, one charge()Counter is 1
In the inheritance version, the third line needs a new object and the last needs a subclass.