all Python 3OOPfunction
__setitem__
magic methods
The method behind item assignment: obj[k] = v calls obj.__setitem__(k, v).
Syntax
def __setitem__(self, key, value): ...
Without __setitem__ item assignment raises TypeError: 'object does not support item assignment' — the way tuples and strings behave. The companion __delitem__ handles del obj[k]. __setitem__ is a natural place to validate the value before storing it.
Examples
class Grades:
def __init__(self):
self._data = {}
def __setitem__(self, name, score):
if not 0 <= score <= 100:
raise ValueError(f'оценка {score} вне 0..100')
self._data[name] = score
def __getitem__(self, name):
return self._data[name]
g = Grades()
g['Анна'] = 95
print(g['Анна']) # → 95
g['Борис'] = 120 # → ValueError: оценка 120 вне 0..100
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy