Junior — Middle
How is object lifetime management handled in Python and what stages does its lifecycle include?
sobes.tech AI
Answer from AI
In Python, object lifetime management is based on reference counting and a garbage collector for cyclic references.
The lifecycle of an object includes the following stages:
- Creation — the object is created in memory, and space is allocated.
- Usage — the object is accessible through references (variables).
- Reference counting — when a reference is created or assigned, the counter increases; when a reference is deleted, it decreases.
- Deletion — when the reference count of an object reaches zero, the memory is freed.
- Garbage collection — for objects involved in cyclic references, a separate garbage collection mechanism periodically searches for and deletes such objects.
Example:
class MyClass:
def __del__(self):
print('Object deleted')
obj = MyClass() # Creating an object
ref = obj # Increasing reference count
del obj # Decreasing reference count
del ref # Reference count becomes 0, object is deleted
Thus, the lifetime of an object in Python is managed automatically, which simplifies memory management.