August 2019
Beginner
482 pages
12h 56m
English
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.