Objects in Python go through a life from creation to removal. Understanding this helps you manage memory and program behavior better.
0
0
Object lifecycle overview in Python
Introduction
When you want to know how and when your data is stored and removed.
When you need to clean up resources like files or network connections.
When debugging why some objects still use memory.
When learning how Python manages your program's data automatically.
Syntax
Python
class ClassName: def __init__(self): # called when object is created pass def __del__(self): # called when object is about to be destroyed pass
__init__ is the constructor method called when an object is created.
__del__ is the destructor method called when an object is about to be removed.
Examples
This creates a Car object and prints messages when created and destroyed.
Python
class Car: def __init__(self): print('Car created') def __del__(self): print('Car destroyed') my_car = Car()
Shows how to pass data when creating an object and track its lifecycle.
Python
class Book: def __init__(self, title): self.title = title print(f'Book "{self.title}" created') def __del__(self): print(f'Book "{self.title}" destroyed') novel = Book('Python Guide')
Sample Program
This program creates a Person object, does some work, then deletes the object explicitly to show the destruction message.
Python
class Person: def __init__(self, name): self.name = name print(f'Person {self.name} created') def __del__(self): print(f'Person {self.name} destroyed') p = Person('Alice') print('Doing some work...') del p print('End of program')
OutputSuccess
Important Notes
Python automatically removes objects when no references point to them.
The __del__ method is not guaranteed to run immediately when you delete an object.
Use del to remove references, but Python's garbage collector decides when to free memory.
Summary
Objects are created with __init__ and destroyed with __del__.
Understanding object lifecycle helps manage resources and memory.
Python handles most cleanup automatically, but you can control it when needed.