Object Lifecycle
The life cycle of an object consists of three basic steps:
- creation
- handling
- destruction
The step of creation
The first life step of an object is the definition of the class to which it belongs. The next step is the instantiation of an instance, through the magic __init__ method. The memory is allocated to hold the object, but shortly before it is called the magic __new__ method (it is rarely overwritten). After these steps, the object is ready to be manipulated.
The step of destruction
When an object is destroyed, the allocated memory is freed and can be reused for other purposes. The destruction of an object occurs when its reference count come back to be zero (an internal variable that takes into account all the active references of an object). In fact, when there is no longer any reference to an object, it is natural that the object must be definitively removed.
The del clause is used to delete an object. You can redefine the corresponding magic method __del__.
The process of removing objects when they are no longer needed is called garbage collection.
⇐Go to Python Lesson 7.2 – Inheritance
Go to Python Lesson 7.5 – Data Hiding⇒