Concepts / Object Attributes and Methods

Object Attributes and Methods

Objects have a complete lifecycle: creation (via __init__), active use, and destruction (via __del__). Python calls these special methods automatically.

  • Programming

The Object Lifecycle

An object has a lifecycle with three broad stages. Python creates the object and calls __init__, your program uses the object's attributes and methods, and Python eventually destroys the object. If the class defines __del__, Python calls that method just before destruction.

Object creation__init__ runsActive objectattributes and methodsFinal cleanup__del__ runsDestroyed objectobject vanishesinitializeno longer neededdestroy
What happens to an object, and in what order, from initialization through active use to destruction?

The important distinction is between active use and final cleanup. While an object is active, your code can access its attributes and call its methods. When Python decides that the object is no longer needed, the object enters its final moment. A defined __del__ method can perform cleanup then, but it cannot prevent the object from being destroyed.

Watching Initialization and Cleanup

Code walkthrough
class PartyAnimal:
    def __init__(self, x):
        self.x = x
        print("created", self.x)

    def __del__(self):
        print("destroyed", self.x)

animal = PartyAnimal(7)
print("using", animal.x)
animal = 42
  1. 1
    Python creates a PartyAnimal object and automatically calls __init__.
  2. 2
    The constructor sets self.x to 7 and prints a creation message.
  3. 3
    The program accesses animal.x while the object is active.
  4. 4
    The assignment animal = 42 replaces the variable's previous object reference with the integer value 42.
  5. 5
    Python decides that the original object is no longer needed, calls __del__, and then destroys that object.
  • __init__ stores the starting value in the object's x attribute.
  • The object can be used through the animal variable.
  • Reassignment makes the original PartyAnimal object no longer available through animal.
  • __del__ performs its final print before the original object is destroyed.
Output
created 7
using 7
destroyed 7

What do you think happens?

What message appears after animal = 42?

  • created 42

  • using 7

  • destroyed 7

Reveal answer
Answer:

destroyed 7

The object's x attribute was set to 7 during initialization. Reassigning animal does not change that old object's attribute; it removes the variable's reference to the object, which triggers final cleanup when Python decides the object is no longer needed.

Programanimal = 42PartyAnimalx = 7__del__cleanupDestroyed objectreplaces variable valueno longer neededfinal cleanup complete
How does reassigning the only variable referring to an object cause final cleanup to run?

Automatic Special Methods

Definition

__init__ and __del__ are special methods that Python calls automatically at important points in an object's lifecycle. __init__ runs when an object is created and gives the class a place to initialize attributes and prepare resources. __del__ runs just before an object is destroyed and gives the class a final opportunity to release resources or perform cleanup.

Object creation__init__initial valuesObject usemethods and attributes__del__final cleanupObject no longerneededreassignment, scope, orprogram endObject destructioncallsreturns to programlifecycle continuesif definedfinal step
Which lifecycle events cause Python to call __init__ and __del__ automatically?

Other Destruction Triggers

Reassignment is only one common trigger. An object can also become no longer needed when a variable goes out of scope, such as when a function returns and a local variable ceases to exist. A third trigger is program termination: Python destroys remaining objects before the program exits, calling __del__ for objects whose classes define it.

SituationWhat changesRole of __del__
Variable reassignmentThe variable is assigned a different valueProvides final cleanup for the old object when Python decides it is no longer needed
Variable leaves scopeA local variable ceases to exist after a function returnsProvides final cleanup for the object that is no longer needed
Program terminationThe program is endingProvides final cleanup for remaining objects before exit

Common situations that can lead to object destruction

Edge case

The key event is not simply that a variable name exists or disappears. The destructor is invoked when Python decides the object is no longer needed. Therefore, trace what happens to the object during reassignment, scope changes, and program termination rather than assuming that __del__ runs immediately after every ordinary operation.

Common Destructor Mistakes

  • Common mistake

    Assuming every class needs a __del__ method.

    What it looks like

    Adding a destructor to a simple object that only stores ordinary Python values.

    Why it fails

    Python's garbage collector automatically reclaims memory for objects that are no longer in use.

    Do this instead

    Use __del__ when the object manages an external resource that needs final cleanup.

  • Common mistake

    Thinking __del__ prevents destruction.

    What it looks like

    Treating the destructor as a way to keep the object alive.

    Why it fails

    The destructor only provides a final opportunity to perform cleanup; it cannot stop the object from being destroyed.

    Do this instead

    Place the necessary final cleanup in __del__, then allow the object's lifecycle to finish.

  • Common mistake

    Expecting __del__ to run while the object is still being used.

    What it looks like

    Trying to use the object as though it remains active after Python has begun its final destruction step.

    Why it fails

    __del__ is called just before destruction, not during ordinary active use.

    Do this instead

    Separate normal methods for active work from __del__ for final cleanup.

  • Common mistake

    Tracing only the variable name and ignoring the object.

    What it looks like

    Assuming that animal = 42 changes the old object's x attribute to 42.

    Why it fails

    The assignment gives animal a different value; it does not modify the old object's stored x value.

    Do this instead

    Trace the old object's attributes separately from the new value assigned to the variable.

Trace the Lifecycle

MEDIUM

Write down the lifecycle sequence for a class that defines both __init__ and __del__. Then identify which event triggers destruction in each case: assigning a new value to the only variable holding the object, returning from a function that created a local object, and reaching the end of the program.

Hints
  • Start with object creation and __init__.
  • Place ordinary attribute access and method calls during the active-use stage.
  • Put __del__ immediately before destruction.
  • For each trigger, ask when Python decides that the object is no longer needed.
Worked example

Tracing one reassignment

A class creates an object with x equal to 12. The only variable holding that object is then assigned a different value. What lifecycle events should be traced?

  1. 1
    Creation

    Python creates the object and automatically calls __init__, which sets the object's initial attribute x to 12.

  2. 2
    Active use

    The program can access the object's x attribute and call its methods while the object is active.

  3. 3
    Reassignment

    The variable is assigned a different value, so it no longer holds the original object.

  4. 4
    Final cleanup

    Python decides the original object is no longer needed and calls __del__ if the class defines it.

  5. 5
    Destruction

    After the final cleanup opportunity, Python destroys the original object.

Result

The sequence is creation and __init__, active use, reassignment, __del__, and destruction.

Key Takeaways

  1. 1
    An object's lifecycle moves from creation through active use to destruction.
  2. 2
    __init__ runs automatically during creation and initializes attributes or prepares resources.
  3. 3
    __del__ runs just before destruction when Python decides the object is no longer needed.
  4. 4
    Reassignment, leaving scope, and program termination can lead to destruction.
  5. 5
    Most objects do not need __del__; it is mainly useful for final cleanup of external resources.

At a glance

  • Python automatically calls __init__ when an object is created.
  • An object remains active while code accesses its attributes and calls its methods.
  • Python calls __del__ just before destroying an object when it is no longer needed.
  • Reassignment, scope changes, and program termination are common destruction triggers.
  • Destructors are uncommon because Python manages memory automatically; they are most useful for external-resource cleanup.

Related concepts

More concepts starting with O