__len__

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
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset