Wikipedia says, ” In computer science, the object lifetime (or life cycle) of an object in object-oriented programming is the time between an object’s creation (also known as instantiation or construction) till the object is no longer used, and is destructed or freed. ”
Typically, an object goes through the following phases during it’s lifetime:
- Allocating memory space
- Binding or associating methods
Similar is the case with Python (ofcourse, the programming constructs used would be different because of language semantics). Let’s see what happens in Python.
Python defines its classes with keywowd ‘class’ which is defined in Python interpretor.
When an instance of the class is created, __init__ method defined in the class is called. It initializes the attributes for newly created class instance. A namespace is also allocated for object’s instance variables. __new__ method is also called where the instance gets created.
Step3: Access and Manipulation
Methods defined in a class can be used for accessing or modifying the state of an object. These are accessors and manipulators respectively. A class instance is used to call these methods.
Every object that gets created, needs to be destroyed. This is done with Python garbage collection (that is reference counting).
Let’s take an example of sample code
self.a = a
self.b = b
obj = Add(3,4)
## Garbage collection