Special Method Protocols
__setitem__() — containers protocol
Implement obj[key] = value. Validate or delegate key and value handling. Slice assignment is optional and requires interpreting slice objects.
Formal Syntax & Structure
python syntaxpython
def __setitem__(self, key, value):Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | object | Index, slice or key. |
| value | object | Assigned value. |
Return Value
None
No meaningful assignment result.
Working Example
Example Snippetpython
class Bag: def __init__(self): self.items=[1,2] def __setitem__(self,key,value): self.items[key]=value
def demo(): b=Bag(); b[0]=7 return b.itemsprint(demo())