Special Method Protocols
__getitem__() — containers protocol
Implement obj[key], including slice objects when supported. Sequence implementations should raise IndexError at invalid positions, mappings KeyError for absent keys. Legacy iteration can fall back to consecutive integer indices.
Formal Syntax & Structure
python syntaxpython
def __getitem__(self, key):Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | object | Index, slice or mapping key. |
Return Value
object
Selected item or slice.
Working Example
Example Snippetpython
class Bag: def __init__(self): self.items=[4,7,9] def __getitem__(self,key): return self.items[key]print(Bag()[1:])