Python __getitem__, commonly referred to as a magic or dunder method, allows objects to be accessed using square brackets [ ]
. This technique can be found in custom classes that represent objects using index-based access methods; we will explore what this method does and its significance within programming with Python in this article.
The primary goal of the __getitem__
method is to set how instances of a class should behave when accessed using square brackets and an index or key, supporting Python’s built-in data types such as lists, strings, dictionaries and others that use indexing protocols such as indexes.
Implementing the __getitem__
method, you can give instances of your custom class the appearance and behavior of sequences or collections, creating an easily understandable interface for users of your class.
In general, __getitem__
can be defined within a class using this syntax:
def __getitem__(self, key):# Define how the object should behave when accessed using key# Return the value associated with the key or index
Let’s use an easy example to demonstrate the use of __getitem__
with a custom class representing a list-like object:
class CustomList:def __init__(self):self.data = []def __getitem__(self, index):return self.data[index]def __len__(self):return len(self.data)def append(self, value):self.data.append(value)# Creating an instance of CustomListmy_list = CustomList()# Appending values to the custom listmy_list.append(1)my_list.append(2)my_list.append(3)# Accessing elements using square bracketsprint(my_list[0]) # Output: 1print(my_list[1]) # Output: 2print(my_list[2]) # Output: 3# Using len() function with custom listprint(len(my_list)) # Output: 3
__getitem__
method to provide index-based access to its data attribute.__len__
method was implemented so instances of CustomList could use len()
function in len()
function with instances.CustomList
, add values using square brackets, and access elements just like a regular list.The __getitem__
method can come in handy in numerous scenarios.
__getitem__
allows easy access to elements within these structures.__getitem__
and similar magic methods.Python __getitem__ method is a powerful tool used for customizing how objects of a class are accessed using square brackets. We can make our custom classes behave like built-in data types using this method, it also provides a seamless and intuitive experience to users of our code. Using python __getitem__ enhances the versatility of our Python classes and opens up possibilities for creating more expressive and user-friendly code.
Quick Links
Legal Stuff
Social Media