🧩 Object Lifecycle in OOP (Object-Oriented Programming)
The object lifecycle refers to the different phases an object goes through from creation to destruction. It involves the following stages:
1. Creation (Instantiation)
-
This is when an object is created in memory using a constructor.
-
In Python, this is done by calling the class name as a function.
Example:
class Car:
def __init__(self, model):
self.model = model
# Object creation
my_car = Car("Toyota")
- Here, the object
my_caris created, and the constructor__init__is called.
2. Initialization
-
The object is initialized with default or passed values.
-
The constructor (
__init__in Python) is responsible for setting initial values or properties of the object.
Example:
class Car:
def __init__(self, model):
self.model = model # Initializing the object's state
3. Usage
-
After creation, the object is used to perform actions or access data.
-
Methods can be invoked, and the object's state can be modified.
Example:
my_car.start_engine() # Using the object to invoke methods
4. Destruction (Garbage Collection)
-
Once an object is no longer needed, it is destroyed or garbage collected in languages with automatic memory management like Python.
-
In languages like C++ or Java, destructors or finalizers handle object cleanup.
Example in Python:
-
In Python, the garbage collector automatically handles object destruction.
-
When an object goes out of scope or is no longer referenced, Python's garbage collector will reclaim the memory.
# When there are no references to 'my_car', it will eventually be garbage collected.
del my_car
5. Finalization
-
Some programming languages provide a mechanism for executing cleanup tasks when an object is destroyed.
-
In Python, the
__del__method can be used to define cleanup operations before an object is destroyed.
Example:
class Car:
def __del__(self):
print(f"The {self.model} car is being destroyed.")
my_car = Car("Toyota")
del my_car # Output: "The Toyota car is being destroyed."
🔑 Summary of Object Lifecycle Stages:
-
Creation: Object is instantiated using a constructor.
-
Initialization: Initial state is set via the constructor.
-
Usage: Object performs actions using methods or properties.
-
Destruction: Memory is freed when the object is no longer in use (handled by garbage collector in Python).
-
Finalization: Optional cleanup before destruction using
__del__in Python.
Let me know if you need more examples or deeper insights into any of these phases!