
__getitem__ is a method in Python that is called when an object is indexed (obj[key]) or sliced (obj[start:stop]). Defining this method inside a class allows instances of that class to be used like lists or dictionaries.
๐ Basic Usage
class MyList:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
print(f"Called with index: {index}")
return self.data[index]
my_list = MyList([10, 20, 30])
print(my_list[1]) # => Called with index: 1
# => 20
๐ฏ Key Features
- When
obj[key]is called,obj.__getitem__(key)is called automatically. keycan be not only an integer, but also a slice, tuple, string, and more.
โ Slicing Can Also Be Supported
class MyList:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
print(f"Index received: {index}")
return self.data[index]
lst = MyList([1, 2, 3, 4, 5])
print(lst[1:4]) # ์ฌ๋ผ์ด์ค ๊ฐ์ฒด(slice(1,4,None))๊ฐ ์ ๋ฌ๋จ
๐ฆ Example: Mimicking a Two-Dimensional Array
class Matrix:
def __init__(self, rows):
self.rows = rows
def __getitem__(self, index):
return self.rows[index]
m = Matrix([[1, 2], [3, 4]])
print(m[0][1]) # 2
โ ๏ธ Notes
__getitem__is read-only. To support writing, you need to define__setitem__.- It is a good idea to handle
KeyError,IndexError, and other exceptions appropriately.
If youโre curious, I can also explain __setitem__ and __delitem__. Would you like to learn more?