Using getitem in Python

Using getitem in Python

__getitem__() is a magic method in python. Magic methods are those methods that are not directly invoked by the programmer when writing a code.

These methods are system calls that are invoked on the back end automatically. The difference between magic and normal methods is that double underscores surround magic methods.

That is why they are also called dunder methods. Dunder here means double underscores. Magic methods are also used for operator overloading.

The use of __getitem__() in a class allows the instances of a class to use the indexer operator [ ] with the reference variables of a class for accessing the value of a list, dictionary, or tuple from a specific index.

This method is automatically invoked when we use the indexer operator with the reference variable of the class. In the following code, we have created a class Person, and in the constructor of the class, we have passed the list of names when creating an object.

We have explicitly defined the __getitem__() method, which takes the list index as an argument and returns the name associated with that index. Here in the code, we have not explicitly called the __getitem__() method.

This method is automatically called when trying to access the value at a certain list index using the [ ] operator. This method is implicitly invoked as p1.__getitem__(1) when we write p1[1] for accessing the values present at index 1 of the list.

Example Code:

# python 3.x
class Person:
    def __init__(self, names):
        self.names=names
    def __getitem__(self,index):
        return self.names[index]
p1=Person(["Jhon", "Kevin"])
print(p1[1])

Output:

# python 3.x
Kevin
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Python Class

  • Python Generator Class
  • Data Class Inheritance in Python
  • Serialize a Python Class Object to JSON
  • Python Abstract Property
  • Python Class Factory
  • Python Class Equality