Method Definition and Calling
Special methods enable custom classes to mimic built-in type behaviors through double-underscore naming conventions.
A Familiar Expression, Hidden Call
A custom object can support familiar operations such as indexing, length checks, arithmetic, and string conversion. The important idea is that Python does not apply these expressions directly to the object in the same way a learner might imagine. Instead, Python recognizes the syntax and automatically translates it into a call to a corresponding special method.
What do you think happens?
What special method does Python use when it evaluates obj[key]?
Reveal answer
Answer: __getitem__
Python translates obj[key] into a call to obj.__getitem__(key). The key or index becomes the method argument, and the method returns the value associated with it.
Expression-to-Method Mapping
Special methods are methods with double-underscore names that Python recognizes for particular operations. For example, len(obj) is translated into obj.__len__(), obj[key] is translated into obj.__getitem__(key), and a + b is translated into a.__add__(b). This translation is automatic and invisible during ordinary use, but it explains how a class can define the behavior of familiar syntax.
| Familiar expression | Underlying special method | Purpose |
|---|---|---|
| obj[key] | obj.__getitem__(key) | Indexing or key-based access |
| len(obj) | obj.__len__() | Length behavior |
| a + b | a.__add__(b) | Addition behavior |
| Printing or string conversion | __str__ | Human-friendly string representation |
Examples of Python expressions and the special methods that define their behavior.
Creation and Cleanup
The object lifecycle includes creation, initialization, and eventual destruction. When a new instance is created, Python automatically calls __init__. This method gives the class a place to initialize the object's state. When an object is about to be destroyed, Python calls __del__, giving the class a chance to clean up resources.
Indexing Through __getitem__
Following a Key Through a Custom Object
A custom class provides __getitem__. A user evaluates obj[key]. What role does the key play?
Start with familiar syntax: The user writes obj[key], using the same square-bracket form associated with lists, tuples, and other indexable objects.
Translate the expression: Python automatically interprets the expression as a call to obj.__getitem__(key).
Receive the argument: The custom method receives the key or index as its argument.
Return the value: The method returns the corresponding value, which becomes the result of obj[key].
Implementing __getitem__ allows a custom object to support familiar square-bracket indexing.
The practical benefit of __getitem__ is interface familiarity. Users of the class can use square brackets instead of learning a separate access operation. The class decides what the key means and which corresponding value to return.
Behaving Like a Built-in
| Desired behavior | Special method | Effect for users |
|---|---|---|
| Initialize object state | __init__ | New instances begin with initialized state |
| Provide indexed access | __getitem__ | Users can write obj[key] |
| Define addition | __add__ | Objects can participate in addition behavior |
| Define comparisons | __eq__ or __lt__ | Objects can participate in equality or less-than behavior |
| Control displayed text | __str__ or __repr__ | Objects have appropriate string representations |
This is the broader purpose of special methods: they let a custom class mimic selected behaviors of built-in Python types. Operator overloading uses methods such as __add__, __sub__, and __mul__ to define arithmetic for custom objects. Comparison methods such as __eq__ and __lt__ define comparison behavior. The class can therefore fit into expressions that users already understand.
String representation follows the same pattern. __str__ is intended to produce a human-friendly representation for end users. __repr__ is intended for developers and should ideally represent the object's state in a form that could be used to recreate it.
Mistakes with Special Methods
Treating obj[key] as unrelated to __getitem__
Python translates obj[key] into obj.__getitem__(key), so the special method defines the custom indexing behavior.
Fix:
When debugging indexing, trace the expression to __getitem__ and check how the method uses the received key.Using __init__ as if it were an ordinary method called manually for every access
__init__ is called automatically when a new instance is created to initialize its state.
Fix:
Associate __init__ with object creation and initialization.Confusing __str__ and __repr__
__str__ is intended for end users, while __repr__ is intended for developers and should ideally represent the object's state in a recreatable form.
Fix:
Use the human-friendly purpose of __str__ and the developer-oriented purpose of __repr__ as the distinction.Assuming an operator has fixed meaning for every custom object
Python translates addition into a.__add__(b), so a class can define what addition means for its objects.
Fix:
When analyzing an operator on a custom object, identify the corresponding special method.
Practice the Translation
For each expression, name the special method Python uses to define the relevant behavior: len(obj), obj[key], a + b, and a == b. Then explain which lifecycle method initializes a new object and which method provides cleanup when an object is about to be destroyed.
Hints
- Indexing uses the method that receives a key or index.
- Addition is an example of operator overloading.
- Equality and less-than behavior are controlled by comparison special methods.
- Creation and destruction use different lifecycle methods.
Checking Your Trace
Match four expressions to their special methods.
Length: len(obj) maps to obj.__len__().
Indexing: obj[key] maps to obj.__getitem__(key).
Addition: a + b maps to a.__add__(b).
Equality: Equality behavior is associated with __eq__.
The expression is the user-facing form; the special method is the class-level behavior Python invokes for that operation.
Key Takeaways
- Special methods use double-underscore names to connect custom classes with familiar Python behavior.
- Python automatically translates expressions such as len(obj), obj[key], and a + b into calls to specific special methods.
- __init__ initializes an object's state during creation, while __del__ provides an opportunity for cleanup when the object is about to be destroyed.
- __getitem__ enables custom objects to support square-bracket indexing.
- Methods such as __add__, __eq__, __str__, and __repr__ define arithmetic, comparison, and string-representation behavior.
Key Takeaways
- Special methods allow custom classes to mimic selected built-in type behaviors.
- Python automatically maps familiar expressions to special method calls.
- __init__ and __del__ connect class behavior to object creation and destruction.
- __getitem__ turns square-bracket access into customizable indexing behavior.
- Operator and representation methods let custom objects participate naturally in expressions and display operations.