__getitem__() is a special method (also known as a dunder or magic method) in Python that allows us to access an element from an object using square brackets, similar to how we access items in a list, tuple, or dictionary. It is commonly used to retrieve items from containers or objects that support indexing or key-based access.
Example: Implementing __getitem__ in a Custom Class
Python
class MyList:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
# Create an instance of MyList
a = MyList([1, 2, 3, 4, 5])
# Accessing items using square brackets
print(a[2])
Explanation:
- We define a custom class MyList that simulates the behavior of a list.
- The __getitem__() method is used to access elements from the data list stored inside the object.
- The method allows us to use the object like a normal list, and my_list[2] internally calls my_list.__getitem__(2) to return the value 3.
Syntax
def __getitem__(self, key):
Parameters
- key: The argument key can be any type depending on the object. For example:
- For lists and tuples, it can be an integer representing the index.
- For dictionaries, it can be any hashable type representing the key.
- For custom objects, it can be any value that the object is designed to handle (like a string, a tuple, etc.).
Return Value
The method must return the value associated with the given key. This value can be any type, depending on the implementation of the __getitem__() method.
Examples of __getitem__()
1. Demonstrating __getitem__()
with Various Indexing Types in Python
This code demonstrates the use of the __getitem__() method in Python, which allows an object to define its behavior when accessed using square brackets. The __getitem__() method is invoked whenever an element is accessed with indexing or slicing, enabling custom handling of such operations.
Python
class Test(object):
def __getitem__(self, items):
print (type(items), items)
# Driver code
test = Test()
test[5]
test[5:65:5]
test['GeeksforGeeks']
test[1, 'x', 10.0]
test['a':'z':2]
test[object()]
Output<class 'int'> 5
<class 'slice'> slice(5, 65, 5)
<class 'str'> GeeksforGeeks
<class 'tuple'> (1, 'x', 10.0)
<class 'slice'> slice('a', 'z', 2)
<class 'object'> <object object at 0x7fad129141f0>
Explanation:
- The __getitem__() method prints the type of the passed item and the item itself.
- The type() function will print the type of the items argument, and the items itself will be printed directly.
2. Implementing __getitem__ for Dictionary-Like Access
This code demonstrates how to implement the __getitem__() method in a custom dictionary-like class, allowing access to dictionary values using square brackets while handling missing keys with a KeyError.
Python
class MyDict:
def __init__(self):
self.data = {"a": 1, "b": 2, "c": 3}
def __getitem__(self, key):
if key in self.data:
return self.data[key]
else:
raise KeyError(f"Key '{key}' not found.")
# Create an instance of MyDict
d = MyDict()
# Accessing elements using square brackets
print(d["b"])
# print(my_dict["d"]) Raises KeyError: Key 'd' not found.
Explanation:
- The class MyDict simulates a dictionary-like structure.
- The __getitem__() method retrieves the value associated with the given key, or raises a KeyError if the key is not present.
- This allows us to use the object as if it were a dictionary, accessing values with square brackets.
Similar Reads
Interview Preparation
Practice @Geeksforgeeks
Data Structures
Algorithms
Programming Languages
Web Technologies
Computer Science Subjects
Data Science & ML
Tutorial Library
GATE CS