The front desk at Riverside Pool is getting a tablet. When Priya Nair walks up with her ten-swim card, the tablet shows what checking in will do before she taps in: the line the desk will see and the swims she’ll have left. Until she taps, her card mustn’t change, so the tablet runs the check-in on a copy.
Python’s copy module handles that, and JavaScript has a deep copy function too. In this lesson, you’ll see why that function can’t copy a class instance and how a JavaScript class says how it’s copied.
Preview a Check-In in Python
In the Python module, copy.deepcopy() makes a new TenSwimCard with its own copy of every attribute, so a check-in on the copy leaves Priya’s card alone:
>>> import copy
>>> priya = TenSwimCard(Swimmer("Priya Nair"), 3)
>>> after = copy.deepcopy(priya)
>>> after.check_in()
'Priya Nair checked in (ten-swim card, 2 left)'
>>> print(priya)
Priya Nair (adult): ten-swim card, 3 left
The copy checks in with two swims left, and Priya’s card still shows three. deepcopy() gives back the same kind of object it was handed, so after has every method priya has.
Copy the Card With structuredClone()
In JavaScript, the deep copy function you know is structuredClone(), which copies an object and the data inside it, so a line-by-line port uses it for copy.deepcopy().