Concepts / String Representation of Objects

String Representation of Objects

Its role is to initialize the object's state so the instance is ready to use.

  • Programming

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]?

  • __init__

  • __getitem__

  • __str__

  • __del__

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

Definition

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 operationSpecial methodPurpose
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

Instance creationnew object__init__initialize stateInitialized objectusable instanceObject destructionabout to be destroyed__del__cleanup opportunityautomatic callstate initializedlifecycle reaches cleanupautomatic call
What happens to an object from creation through initialization to cleanup, and when are __init__ and __del__ involved?

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.

Worked example

Tracing a Managed Object

A custom class represents an object that needs state during its lifetime. Which special methods belong to setup and cleanup?

  1. 1
    Create the instance

    When a new instance is created, Python automatically calls __init__.

  2. 2
    Set the initial state

    The class uses __init__ to initialize the state that the object needs while it is being used.

  3. 3
    Reach destruction

    When the object is about to be destroyed, Python calls __del__.

  4. 4
    Perform cleanup

    The class can use __del__ as an opportunity to clean up resources associated with the object.

Result

__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.

MethodPrimary audienceRepresentation goal
__str__End usersHuman-friendly string representation
__repr__DevelopersA 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 like

    Thinking that the programmer must explicitly call __getitem__ before using obj[key]

    Why it fails

    Python automatically translates obj[key] into obj.__getitem__(key).

    Do this instead

    Define the appropriate special method in the class, then use the corresponding Python syntax.

  • Common mistake

    Using __init__ to describe cleanup

    What it looks like

    Assigning 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 instead

    Use __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 like

    Designing 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 instead

    Choose a human-friendly __str__ representation and a developer-oriented __repr__ representation.

  • Common mistake

    Forgetting that indexing requires a returned value

    What it looks like

    Defining __getitem__ without reasoning about the value it should provide for the requested key or index

    Why it fails

    The purpose of __getitem__ is to receive the key or index and return the corresponding value.

    Do this instead

    Design __getitem__ around the mapping from the requested key or index to the value the caller should receive.

Practice the Translation

MEDIUM

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__.
Worked example

Checking the Mapping

Explain the hidden special-method call behind item[position].

  1. 1
    Recognize the syntax

    The square brackets show that the expression is using indexing.

  2. 2
    Find the matching method

    Indexing on a custom object is connected to __getitem__.

  3. 3
    Pass the requested key

    Python translates the expression into item.__getitem__(position), so the key or index becomes the method argument.

  4. 4
    Return the corresponding value

    The special method should return the value associated with the requested key or index.

Result

item[position] is automatically translated into item.__getitem__(position).

Key Takeaways

  1. 1
    Special methods use double-underscore names to connect custom classes with Python syntax and built-in operations.
  2. 2
    Python automatically translates expressions such as len(obj), obj[key], and a + b into calls to corresponding special methods.
  3. 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. 4
    __getitem__ enables indexing behavior, allowing a custom class to use familiar square-bracket notation.
  5. 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.

Related concepts

More concepts starting with S