String Representation of Objects
Its role is to initialize the object's state so the instance is ready to use.
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
__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?
- 1Create the instance
When a new instance is created, Python automatically calls
__init__. - 2Set the initial state
The class uses
__init__to initialize the state that the object needs while it is being used. - 3Reach destruction
When the object is about to be destroyed, Python calls
__del__. - 4Perform 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 |
The different purposes of __str__ and __repr__
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
Common mistake Treating special methods as ordinary methods that must be called manually for every operation
What it looks likeThinking that the programmer must explicitly call __getitem__ before using obj[key]
Why it failsPython automatically translates obj[key] into
obj.__getitem__(key).Do this insteadDefine the appropriate special method in the class, then use the corresponding Python syntax.
Common mistake Using __init__ to describe cleanup
What it looks likeAssigning both initial setup and resource cleanup responsibilities to __init__
Why it fails__init__is called when a new instance is created, while__del__is called when an object is about to be destroyed.Do this insteadUse __init__ for initial state and __del__ for the cleanup opportunity associated with destruction.
Common mistake Assuming __str__ and __repr__ serve exactly the same audience
What it looks likeDesigning every string representation only for developers or only for end users
Why it fails__str__is intended for end users, while__repr__is intended for developers.Do this insteadChoose a human-friendly __str__ representation and a developer-oriented __repr__ representation.
Common mistake Forgetting that indexing requires a returned value
What it looks likeDefining __getitem__ without reasoning about the value it should provide for the requested key or index
Why it failsThe purpose of
__getitem__is to receive the key or index and return the corresponding value.Do this insteadDesign __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].
- 1Recognize the syntax
The square brackets show that the expression is using indexing.
- 2Find the matching method
Indexing on a custom object is connected to
__getitem__. - 3Pass the requested key
Python translates the expression into
item.__getitem__(position), so the key or index becomes the method argument. - 4Return 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
- 1Special methods use double-underscore names to connect custom classes with Python syntax and built-in operations.
- 2Python automatically translates expressions such as
len(obj), obj[key], and a + b into calls to corresponding special methods. - 3
__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. - 4
__getitem__enables indexing behavior, allowing a custom class to use familiar square-bracket notation. - 5
__str__provides a human-friendly representation, while__repr__provides a developer-oriented representation of an object's state.
At a glance
- 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.