Sharing Prices and Factories With static
Priya Nair’s ten-swim card needs its price: £45 for ten swims. Every card shares that price, so
the Python module keeps it on the class, as two class attributes, and cost_per_swim() reads them
through self:
class TenSwimCard:
PRICE = 45
SWIMS = 10
def __init__(self, swimmer, swims_left=10):
self.swimmer = swimmer
self._swims_left = swims_left
def cost_per_swim(self):
return self.PRICE / self.SWIMS
swimmer = Swimmer("Priya Nair")
priya = TenSwimCard(swimmer, 3)
cost = priya.cost_per_swim()
print(f"Ten-swim card: £{cost:.2f} a swim")
Python prints Ten-swim card: £4.50 a swim.
In JavaScript, a value that belongs to the class is a static field: you write static in
front of it. From outside, you read it through the class, TenSwimCard.PRICE, as in Python.
The method ports the way Python reads the price, with this for self, and .toFixed(2) rounds
the cost to two places and gives back text, as :.2f does: