The __getitem__
method in Python is a special method used to define how objects of a class handle indexing operations. By implementing the __getitem__
method, you can customize how items are accessed using square bracket notation (e.g., obj[key]
). This method allows your classes to behave like containers or sequences, enabling more intuitive data retrieval.
__getitem__
Method WorksThe __getitem__
method is called when an item is accessed using the square bracket notation. It should return the value associated with the specified index or key.
**self**
: The instance of the class on which indexing is performed.**key**
: The index or key used to access an item. This can be an integer, a string, or any other hashable object, depending on the use case.In this example, the __getitem__
method allows MyList
objects to support indexing with integers, returning the corresponding element from the list.
You can also use __getitem__
for objects that support key-based indexing, such as dictionaries.
In this example, __getitem__
enables MyDict
objects to handle key-based indexing similarly to dictionaries, returning values associated with the given keys.
__getitem__
Method__getitem__
to create custom container classes that support indexing and key-based access, making them behave like lists, dictionaries, or other sequence-like structures.__getitem__
to provide a user-friendly way to access data within your objects, allowing for flexible and intuitive retrieval mechanisms.__getitem__
method can also handle slicing operations if the key
is a slice
object, enabling more advanced indexing features.In this example, __getitem__
handles both integer indexing and slicing for MyRange
objects.
The __getitem__
method in Python is a powerful tool for customizing how objects handle indexing and key-based access. By implementing this method, you can create classes that behave like containers or sequences, allowing for intuitive data retrieval using square bracket notation. Whether you're dealing with integer indexing, key-based access, or slicing, __getitem__
enhances the flexibility and usability of your custom classes in Python.