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
__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?
- 1Start with familiar syntax
The user writes obj[key], using the same square-bracket form associated with lists, tuples, and other indexable objects.
- 2Translate the expression
Python automatically interprets the expression as a call to
obj.__getitem__(key). - 3Receive the argument
The custom method receives the key or index as its argument.
- 4Return 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 |
Special methods connect custom class behavior with familiar Python operations.
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
Common mistake Treating obj[key] as unrelated to __getitem__
What it looks likeA learner sees square-bracket access as ordinary syntax and does not look for __getitem__ when investigating a custom class.
Why it failsPython translates obj[key] into
obj.__getitem__(key), so the special method defines the custom indexing behavior.Do this insteadWhen debugging indexing, trace the expression to __getitem__ and check how the method uses the received key.
Common mistake Using __init__ as if it were an ordinary method called manually for every access
What it looks likeA learner expects __init__ to run whenever an object is used.
Why it fails__init__is called automatically when a new instance is created to initialize its state.Do this insteadAssociate __init__ with object creation and initialization.
Common mistake Confusing __str__ and __repr__
What it looks likeA learner gives both methods the same purpose without considering the intended audience.
Why it fails__str__is intended for end users, while__repr__is intended for developers and should ideally represent the object's state in a recreatable form.Do this insteadUse the human-friendly purpose of __str__ and the developer-oriented purpose of __repr__ as the distinction.
Common mistake Assuming an operator has fixed meaning for every custom object
What it looks likeA learner assumes a + b must have the same meaning for all classes.
Why it failsPython translates addition into
a.__add__(b), so a class can define what addition means for its objects.Do this insteadWhen 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.
- 1Length
len(obj)maps toobj.__len__(). - 2Indexing
obj[key] maps to
obj.__getitem__(key). - 3Addition
a + b maps to
a.__add__(b). - 4Equality
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
- 1Special methods use double-underscore names to connect custom classes with familiar Python behavior.
- 2Python automatically translates expressions such as
len(obj), obj[key], and a + b into calls to specific special methods. - 3
__init__initializes an object's state during creation, while__del__provides an opportunity for cleanup when the object is about to be destroyed. - 4
__getitem__enables custom objects to support square-bracket indexing. - 5Methods such as
__add__,__eq__,__str__, and__repr__define arithmetic, comparison, and string-representation behavior.
At a glance
- 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.