__setitem__ and __getitem__ in Python with example

In this tutorial, we will learn about two important methods in Python. They are Python __setitem__ and __getitem__. We will also see how to use them with an example.

Both __setitem__ and __getitem__ are magic methods in Python. Magic methods have two underscores in the prefix and suffix of the method name. They are generally used for operator overloading.

__setitem__ and __getitem__ magic methods

__setitem__ is a method used for assigning a value to an item. It is implicitly invoked when we set a value to an item of a list, dictionary, etc. __getitem__ is a method used for getting the value of an item. It is implicitly invoked when we access the items of a list, dictionary, etc. We can overload their operations by explicitly defining them.

Example of using these methods

Look at the code below:

class Student:   
    def __init__(self,size):
        self.stu=[None]*size

    def __setitem__(self,rollno,name):
        #explicitly defined __setitem__
        print("Setting name to rollno",rollno)
        self.stu[rollno]=name
        
    def __getitem__(self,rollno):
        #explicitly defined __getitem__
        print("Getting name associated with rollno",rollno)
        return self.stu[rollno]
    
s1=Student(4)

s1[0]='Meghana'
s1[1]='Raju'
s1[2]='Hari'
s1[3]='Sreeja'
print(s1[0])
print(s1[0:4])

Here, we created an object for the class Student called s1. Using the __init__ method we have created a list and assigned ‘None’ value to each element of the list. Next, when we are assigning values(s1[0]=’Meghana’) the __setitem__ method is implicitly invoked as s1.__setitem__(0,’hi’). Next, when we are accessing(s1[0]) the items the __getitem__ method is implicitly invoked as s1.__getitem__(0).

Output:

Setting name to rollno 0
Setting name to rollno 1
Setting name to rollno 2
Setting name to rollno 3
Getting name associated with rollno 0
Meghana
Getting name associated with rollno slice(0, 4, None)
['Meghana', 'Raju', 'Hari', 'Sreeja']

Also, read: Use destructors in Python

Leave a Reply

Your email address will not be published. Required fields are marked *