Posts tagged magic methods
Use magic methods __setitem__() and __getitem__() in Python
- 30 September 2023
In Python, there are two magic methods that can be used to implement the behavior of the subscript operator []
. These methods are object.__setitem__()
and object.__getitem__()
. The first one is used to assign a value to an item, the second one is used to retrieve an item.
The following example shows how to use these methods to implement a memory class as a list of bytes that was used in the 6502 emulator. The memory class has two methods get()
and set()
that are used to retrieve and assign a value to a memory address.