__getitem__ and __setitem__ in Python

__getitem__ and __setitem__ in Python

In Python, __getitem__ and __setitem__ are special (or "dunder") methods that can be defined in a class to customize the behavior of indexing (i.e., accessing items using square brackets []).

1. __getitem__

This method is used to retrieve an item from an object. When an object of the class is indexed using square brackets, the __getitem__ method is called with the index as its argument.

Example:

class MyClass: def __getitem__(self, index): return index ** 2 obj = MyClass() print(obj[4]) # Outputs: 16 (because 4 squared is 16) 

2. __setitem__

This method is used to set the value of an item. When you assign a value to an indexed object of the class, the __setitem__ method is called with the index and the value being assigned.

Example:

class MyContainer: def __init__(self): self.data = {} def __setitem__(self, key, value): self.data[key] = value def __getitem__(self, key): return self.data[key] container = MyContainer() container['a'] = 'apple' # Calls __setitem__ print(container['a']) # Calls __getitem__ and outputs: apple 

Practical Example:

Consider a class that represents a simple 2D array:

class Simple2DArray: def __init__(self, rows, cols): self.data = [[None for _ in range(cols)] for _ in range(rows)] def __setitem__(self, index, value): row, col = index self.data[row][col] = value def __getitem__(self, index): row, col = index return self.data[row][col] arr = Simple2DArray(3, 3) arr[1, 2] = 'a' print(arr[1, 2]) # Outputs: a 

With __getitem__ and __setitem__, we can define custom behaviors for getting and setting items, making our objects more Pythonic and intuitive to use.


More Tags

ntp eclipse-classpath selection contour gmail-imap json5 format hashset my.cnf android-navigation

More Programming Guides

Other Guides

More Programming Examples