How to Overload [] Operator in Python: Syntax and Example
In Python, you overload the
[] operator by defining the __getitem__ method to access items and __setitem__ to assign items in your class. These special methods let you customize how your objects behave when using square brackets.Syntax
To overload the [] operator, define these methods in your class:
__getitem__(self, key): Called when accessing an item likeobj[key].__setitem__(self, key, value): Called when assigning an item likeobj[key] = value.
The key can be any type (integer, string, tuple) depending on your use case.
python
class MyClass: def __getitem__(self, key): # Return value for obj[key] pass def __setitem__(self, key, value): # Set value for obj[key] = value pass
Example
This example shows a simple class that stores items in a dictionary and uses __getitem__ and __setitem__ to access and set values with square brackets.
python
class SimpleDict: def __init__(self): self.data = {} def __getitem__(self, key): return self.data.get(key, 'Key not found') def __setitem__(self, key, value): self.data[key] = value obj = SimpleDict() obj['apple'] = 10 obj['banana'] = 20 print(obj['apple']) print(obj['banana']) print(obj['cherry'])
Output
10
20
Key not found
Common Pitfalls
Common mistakes when overloading [] include:
- Not handling missing keys in
__getitem__, which can causeKeyError. - Forgetting to implement
__setitem__if you want to allow assignment. - Using mutable default arguments or shared state incorrectly inside these methods.
Always handle errors gracefully and keep your internal data consistent.
python
class BadExample: def __getitem__(self, key): # This will raise KeyError if key not found return self.data[key] # Missing __setitem__ means obj[key] = value will fail # Correct way: class GoodExample: def __init__(self): self.data = {} def __getitem__(self, key): return self.data.get(key, None) # Returns None if key missing def __setitem__(self, key, value): self.data[key] = value
Quick Reference
Summary tips for overloading [] operator:
- Use
__getitem__(self, key)to define behavior forobj[key]. - Use
__setitem__(self, key, value)to define behavior forobj[key] = value. - Handle missing keys carefully to avoid exceptions.
- Support any key type your use case needs (int, str, tuple, etc.).
Key Takeaways
Overload [] operator by defining __getitem__ and __setitem__ methods in your class.
__getitem__ handles accessing items; __setitem__ handles assigning items.
Always handle missing keys gracefully to avoid errors.
The key parameter can be any type depending on your design.
Implement both methods to fully support bracket access and assignment.