__setitem__

Dunder MethodPython 2.0+Intermediate

Enables item assignment with square brackets (obj[key] = value)

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
class SafeList:
    def __init__(self):
        self._data = {}

    def __setitem__(self, key, value):
        self._data[key] = value
        print(f"Set [{key}] = {value}")

    def __getitem__(self, key):
        return self._data[key]

sl = SafeList()
sl["name"] = "Python"
print(sl["name"])

__setitem__ enables item assignment with square brackets (obj[key] = value). Implementing it lets you customize how Python interacts with your objects.

Try in Playground

Tags

oopmagic-methodprotocolcore