String Representation of Objects
Special methods enable custom classes to mimic built-in type behaviors through double-underscore naming conventions.
From Expression to Method
A custom object can respond to familiar Python syntax such as indexing, length checks, addition, and string conversion. This happens because Python automatically translates standard expressions into calls to specially named methods. These methods use a double-underscore naming convention, so they are commonly called special methods.
What do you think happens?
What special method does Python invoke when a custom object is used in the expression obj[key]?
Reveal answer
Answer: __getitem__
Python translates obj[key] into a call to obj.__getitem__(key). The translation is automatic, so the programmer can use familiar square-bracket notation with a suitable custom class.
Special Methods as a Language Interface
Special methods are methods with double-underscore names that connect a class to Python's built-in operations and syntax. They allow a custom class to mimic the behavior of built-in types while still representing its own kind of object.
| Python expression or operation | Special method | Purpose |
|---|---|---|
| Creating an instance | __init__ | Initialize the object's state |
| An object is about to be destroyed | __del__ | Provide an opportunity to clean up resources |
| obj[key] | __getitem__ | Support indexing or key access |
| len(obj) | __len__ | Provide the object's length |
| a + b | __add__ | Define addition for custom objects |
| String conversion or printing | __str__ and __repr__ | Control the displayed representation |
Common expressions and the special methods Python associates with them
This relationship explains why special methods are useful: users of a class can write familiar expressions, while the class author defines how those expressions should behave. Operator overloading follows the same pattern. For example, implementing __add__ controls what addition means for instances of the custom class. Similar special methods define comparison operations such as __eq__ and __lt__, as well as arithmetic operations such as __sub__ and __mul__.
Object Creation and Cleanup
The __init__ method is called automatically when a new instance is created. Its role is to initialize the object's state so the instance is ready to use. Later, when the object is about to be destroyed, Python calls __del__, giving the class an opportunity to clean up resources. Thinking in terms of this lifecycle helps separate setup work from cleanup work.
Tracing a Managed Object
A custom class represents an object that needs state during its lifetime. Which special methods belong to setup and cleanup?
Create the instance: When a new instance is created, Python automatically calls __init__.
Set the initial state: The class uses __init__ to initialize the state that the object needs while it is being used.
Reach destruction: When the object is about to be destroyed, Python calls __del__.
Perform cleanup: The class can use __del__ as an opportunity to clean up resources associated with the object.
__init__ belongs to object setup, while __del__ belongs to the cleanup stage of the object lifecycle.
Readable Object Representations
When an object is printed or converted to a string, Python uses special methods to determine what should be displayed. The __str__ method is intended to provide a human-friendly representation for end users. The __repr__ method is intended for developers and should ideally describe the object's state in a form that could be used to recreate it.
| Method | Primary audience | Representation goal |
|---|---|---|
| __str__ | End users | Human-friendly string representation |
| __repr__ | Developers | A representation of the object's state that ideally could help recreate it |
A useful design question is who needs to read the representation. If the result is meant to communicate with an end user, __str__ should focus on clarity. If the result is meant to help a developer understand the object's state, __repr__ should focus on a more informative representation.
Mistakes in Special Method Reasoning
Treating special methods as ordinary methods that must be called manually for every operation
Python automatically translates obj[key] into obj.__getitem__(key).
Fix:
Define the appropriate special method in the class, then use the corresponding Python syntax.Using __init__ to describe cleanup
__init__ is called when a new instance is created, while __del__ is called when an object is about to be destroyed.
Fix:
Use __init__ for initial state and __del__ for the cleanup opportunity associated with destruction.Assuming __str__ and __repr__ serve exactly the same audience
__str__ is intended for end users, while __repr__ is intended for developers.
Fix:
Choose a human-friendly __str__ representation and a developer-oriented __repr__ representation.Forgetting that indexing requires a returned value
The purpose of __getitem__ is to receive the key or index and return the corresponding value.
Fix:
Design __getitem__ around the mapping from the requested key or index to the value the caller should receive.
Practice the Translation
For each expression, identify the special method Python associates with it: len(item), item[position], left + right, and conversion of item to a string. Then explain whether the method is primarily related to size, indexing, arithmetic, or representation.
Hints
- The indexing expression uses the method that receives a key or index.
- The addition expression uses the special method for addition.
- String conversion is related to __str__ and object display also involves __repr__.
Checking the Mapping
Explain the hidden special-method call behind item[position].
Recognize the syntax: The square brackets show that the expression is using indexing.
Find the matching method: Indexing on a custom object is connected to __getitem__.
Pass the requested key: Python translates the expression into item.__getitem__(position), so the key or index becomes the method argument.
Return the corresponding value: The special method should return the value associated with the requested key or index.
item[position] is automatically translated into item.__getitem__(position).
Key Takeaways
- Special methods use double-underscore names to connect custom classes with Python syntax and built-in operations.
- Python automatically translates expressions such as len(obj), obj[key], and a + b into calls to corresponding special methods.
- __init__ initializes an object's state when an instance is created, while __del__ is associated with cleanup when an object is about to be destroyed.
- __getitem__ enables indexing behavior, allowing a custom class to use familiar square-bracket notation.
- __str__ provides a human-friendly representation, while __repr__ provides a developer-oriented representation of an object's state.
Key Takeaways
- Special methods are the connection between custom class behavior and Python's built-in syntax.
- Expressions such as obj[key], len(obj), and a + b are automatically mapped to special method calls.
- __init__ and __del__ mark important stages in an object's setup and cleanup lifecycle.
- __getitem__, __str__, and __repr__ make custom objects more usable through indexing and meaningful string representations.