Porting the Pool Passes Module
Riverside Pool’s new online booking is written in JavaScript, so the Python passes module moves
too. It has a Swimmer dataclass, a Pass with a check-in and a printable line, and two kinds of
pass, the ten-swim card and the membership. When you run it, it prints four lines:
Priya Nair (adult): ten-swim card, 3 left
Tom Hale (concession): membership, 6 months
Grace Obi (junior): ten-swim card, 10 left
Ten-swim card: £4.50 a swim
In this lesson, you rebuilt it in JavaScript, class by class:
- The dataclass writes
Swimmer’s__init__()for you. In JavaScript, you write the constructor, with"adult"as the group’s default, and assign each value tothis. Passdeclaresswims = 0as a field. Its constructor takes only the swimmer: there’s noselfin the list, becausethisarrives with the call.- Python’s
__str__()becomestoString(), which JavaScript calls whenever a pass goes into a template literal.console.log()on its own shows the fields, not the line. TenSwimCardkeeps its price and swim count instaticfields, and its swims left in a private#swimsLeftfield behind a getter. Its constructor defaults the swims left through the class name, since a static is a property of the class, never a plain name; Python works out the default while the class body runs, whereSWIMSis a name.super(swimmer)comes first in both subclasses, becausethisdoesn’t exist until it has run, so#swimsLeftandmonthsare set after it.- The card’s
checkIn()throws aRangeErroron an empty card, where Python raises aValueError; otherwise-=takes a swim off andsuper.checkIn()returnsPass’s line. costPerSwim()readsTenSwimCard.PRICE: on a card,this.PRICEisundefined. The class method becomes a static method,fromRecord(), which reads the record’s camelCase key with a dot, where the dict needs brackets.