Concepts / Object Initialization and Cleanup

Object Initialization and Cleanup

Special methods connect a class definition to a language operation. They allow an object created by your class to behave more like a built-in Python type.

  • Programming

The Hidden Work Behind Familiar Syntax

Python lets a custom object participate in familiar operations such as indexing, measuring its length, adding it to another object, and displaying it as text. The connection is made through special methods: methods with names that begin and end with double underscores. Python recognizes particular expressions and automatically translates them into calls to the corresponding special methods.

Key point

Special methods connect a class definition to a language operation. They allow an object created by your class to behave more like a built-in Python type.

obj[key]indexing__getitem__receives keylen(obj)length__len__returns lengthobj + otheraddition__add__receives othertranslates totranslates totranslates to
What special method does Python connect to each familiar expression?

Building an Initial Object State

The __init__ method is called automatically when a new instance of a class is created. Its role is to initialize the object's state, such as assigning the attributes that the object needs at the beginning of its life. You do not normally trigger this method by writing an ordinary method call; creating the instance causes Python to invoke it.

ClassdefinitionNew instanceobject state begins__init__initializes stateInitial attributesready for usecreatecall automaticallyassign
What happens from creating a class instance until __init__ assigns its initial state?
Worked example

Tracing Initial State

A class is designed so that each new instance begins with an initial name and status. Which special method is responsible for establishing those attributes?

  1. 1
    Create the instance

    Creating a new instance causes Python to call the class's __init__ method automatically.

  2. 2
    Receive initialization values

    The __init__ method can use the values supplied for the new instance while setting up its state.

  3. 3
    Assign the initial attributes

    The method establishes the object's initial state by assigning its attributes.

Result

__init__ is the special method responsible for initializing the new object's state.

Connecting Syntax to Behavior

Python syntax provides a convenient surface for working with objects. When the object is custom, Python still recognizes the operation and connects it to a special method. For example, len(obj) becomes a call to obj.__len__(), and obj[key] becomes a call to obj.__getitem__(key). The translation is automatic and invisible while the expression runs.

ExpressionSpecial methodBehavior controlled
obj[key]__getitem__Indexing or key-based access
len(obj)__len__Length
obj + other__add__Addition
Printing or converting an object to text__str__Human-friendly representation
Displaying an object's representation__repr__Developer-oriented representation

Common Python operations and the special methods associated with them

Worked example

Reading a Custom Object with Square Brackets

A custom class defines __getitem__. A learner writes obj[key]. What role does __getitem__ play?

  1. 1
    Recognize the expression

    Square brackets after an object represent indexing or key-based access.

  2. 2
    Translate the operation

    Python connects obj[key] to a call to obj.__getitem__(key).

  3. 3
    Return the value

    The __getitem__ method receives the key or index and should return the corresponding value.

Result

Defining __getitem__ gives the custom object familiar square-bracket access.

Giving Custom Classes Built-In Behaviors

A class can use special methods to make its instances behave like familiar Python values. __getitem__ can provide indexing, __add__ can define what addition means, and other special methods can define subtraction, multiplication, equality, and ordering. This is called operator overloading when special methods define the meaning of operators for custom objects.

ListindexingNumberadditionIndexingobj[key]Custom object__getitem__Custom numeric object__add__Additionobj + othersupportsdefines through __getitem__supportsdefines through __add__
How does defining special methods let a custom object participate in operations associated with built-in types?

The goal is not to make every class imitate every built-in type. Instead, a class defines the special methods that match the behavior its objects should provide. A class representing an indexable collection may define __getitem__; a class representing a value that can be combined with another value may define __add__. The resulting syntax is familiar to users of the class.

The Destruction Stage

The __del__ method is associated with the end of an object's lifecycle. Python calls it when an object is about to be destroyed, giving the class an opportunity to clean up resources. Thinking in lifecycle terms helps separate the setup performed by __init__ from the cleanup associated with __del__.

Reachable objectactive stateUnreachable objectno longer availableAbout to be destroyedcleanup stage__del__cleanup opportunityobject becomeslifecycle advancesPython calls
What changes as an object becomes unreachable and Python approaches its destruction?

Representing Objects as Text

Special methods also determine how an object is represented as text. __str__ is intended to provide a human-friendly string 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. Choosing the appropriate method helps the same object communicate effectively to different audiences.

MethodPrimary audiencePurpose
__str__End usersHuman-friendly string representation
__repr__DevelopersRepresentation of the object's state

The different communication goals of __str__ and __repr__

Mistakes with Special Methods

  • Common mistake

    Treating obj[key] as unrelated to __getitem__

    What it looks like

    A learner sees square-bracket access as syntax that cannot be customized.

    Why it fails

    Python translates obj[key] into a call to obj.__getitem__(key).

    Do this instead

    When designing indexing behavior, identify and implement __getitem__.

  • Common mistake

    Using __init__ as though it were an ordinary method called manually for every initialization

    What it looks like

    A learner overlooks the automatic call that occurs when a new instance is created.

    Why it fails

    __init__ is called automatically when a new instance is created and is responsible for initializing its state.

    Do this instead

    Think of instance creation as the event that triggers __init__.

  • Common mistake

    Confusing __str__ and __repr__

    What it looks like

    A class provides one representation without considering whether the audience is an end user or a developer.

    Why it fails

    __str__ is intended for a human-friendly display, while __repr__ is intended for a developer-oriented representation of state.

    Do this instead

    Choose __str__ for end-user readability and __repr__ for developer-focused state representation.

  • Common mistake

    Assuming operator overloading is limited to addition

    What it looks like

    A learner defines __add__ but does not recognize that other operators can also be customized.

    Why it fails

    Special methods can define subtraction, multiplication, equality, ordering, and other operations as well.

    Do this instead

    Match each desired operator behavior with its corresponding special method.

Applying the Lifecycle Model

EASY

For each expression, identify the special method Python connects to it: obj[key], len(obj), and obj + other. Then describe which special method belongs at the beginning of an object's lifecycle and which belongs near its destruction.

Hints
  • Square brackets indicate key or index access.
  • The length operation has a dedicated special method.
  • The plus operator maps to the special method for addition.
  • Compare the creation stage with the destruction stage.
Worked example

A Complete Special-Method Trace

A custom object is created, accessed with a key, measured, combined with another object, displayed, and eventually reaches destruction. Match each stage to its relevant special method.

  1. 1
    Creation

    __init__ establishes the object's initial state.

  2. 2
    Key access

    obj[key] is connected to __getitem__(key).

  3. 3
    Length

    len(obj) is connected to __len__().

  4. 4
    Combination

    obj + other is connected to __add__(other).

  5. 5
    Text representation

    __str__ supplies a human-friendly representation, while __repr__ supplies a developer-oriented representation.

  6. 6
    Destruction

    __del__ is associated with the point when the object is about to be destroyed.

Result

Special methods provide a systematic bridge between an object's lifecycle or behavior and familiar Python syntax.

What to Remember

  1. 1
    Special methods use double-underscore names to connect class behavior with Python operations.
  2. 2
    __init__ is called automatically when a new instance is created and establishes its initial state.
  3. 3
    __del__ belongs to the destruction stage and provides an opportunity to clean up when an object is about to be destroyed.
  4. 4
    Expressions such as obj[key], len(obj), and obj + other are automatically connected to __getitem__, __len__, and __add__.
  5. 5
    __str__ and __repr__ provide different kinds of object representations for end users and developers.

At a glance

  • Special methods let custom classes mimic selected behaviors of built-in Python types.
  • Python automatically translates familiar expressions into calls to corresponding special methods.
  • __init__ initializes an instance, while __del__ participates in its destruction lifecycle.
  • __getitem__ enables square-bracket access, and __add__ enables custom addition behavior.
  • __str__ and __repr__ serve different audiences when representing an object as text.

Related concepts

More concepts starting with O