Skip to Content
Learn Python by Building Data Science Applications
book

Learn Python by Building Data Science Applications

by Philipp Kats, David Katz
August 2019
Beginner
482 pages
12h 56m
English
Packt Publishing
Content preview from Learn Python by Building Data Science Applications

__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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python for Data Science

Python for Data Science

Yuli Vasiliev
Introduction to Machine Learning with Python

Introduction to Machine Learning with Python

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9781789535365Supplemental Content