__getitem__

This method runs under the hood when someone attempts to retrieve a specific value from an object using square brackets, as if it was a list or dictionary. Let's add one more section to our School class so that we'll be able to get specific fish by their index:

class School:
def __init__(self, *fishes):
self.fishes = list(fishes)

def __getitem__(self, i):
return self.fishes[i]

Now, let's test it:

>>> S = School(Fish(), Fish())
>>> S[0]
<__main__.Fish at 0x104d73d30>

Note that nothing prevents us from adding a different behavior—say, treating the object as a dictionary, and thus using the value in the square brackets as a key.

..................Content has been hidden....................

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