Give objects indexed access and assignment through special methods.
How It Works
__getitem__(self, key) backs obj[key], while __setitem__ handles indexed assignment. Select appropriate errors: IndexError for invalid sequence indexes, KeyError for missing mapping keys.
__delitem__ can add deletion support when needed.
Step-by-Step Example
class ScoreBook:
def __init__(self):
self.scores = {}
def __getitem__(self, student_name):
return self.scores[student_name]
def __setitem__(self, student_name, score):
self.scores[student_name] = score
score_book = ScoreBook()
score_book["Morgan"] = 92
print(score_book["Morgan"])
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
92
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Build a simple record wrapper that supports both lookup and assignment.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Assuming __getitem__ implements assignment automatically without __setitem__.
- Raising a misleading exception type for a missing key or invalid sequence index.
Key Takeaways
- Give objects indexed access and assignment through special methods.
- __getitem__(self, key) backs obj[key], while __setitem__ handles indexed assignment.
- __delitem__ can add deletion support when needed.