__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
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 for accessing the values present at index
1 of the list.
# 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)
# python 3.x Kevin