August 2019
Beginner
482 pages
12h 56m
English
Earlier, we built a School class that groups multiple fish together. There are a few special methods that can be used on classes if they represent a collection. The __len__ method, as you can guess, represents the length of the object, and runs whenever the built-in len function is called on the object. Let's modify our School class to return the number of fish:
class School: def __init__(self, *fishes): self.fishes = list(fishes) def __len__(self): return len(self.fishes)
Now, let's recreate School of two fish and see how it will work:
>>> S = School(Fish(), Fish())>>> len(S)2
Read now
Unlock full access