Object lifetime in Python


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:

  1. Allocating memory space
  2. Binding or associating methods
  3. Initialization
  4. Destruction

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.

Step1: Definition

Python defines its classes with keywowd ‘class’ which is defined in Python interpretor.

Step2: Initialization

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.

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.

Step4: Destrcution

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

## Definition
class Add:
## Initialization
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def add(self):
        return self.a+self.b
obj = Add(3,4)
## Access
print obj.add()
## Garbage collection
About these ads

About Chetan Giridhar

An avid technologist, blogger and a newbie photographer.

Posted on January 17, 2012, in Blog and tagged , , , , , , , . Bookmark the permalink. 2 Comments.

  1. hey, in the example above, when does the object get destroyed?
    thanks!

  2. Here’s a statement from Python documentation “Circular references which are garbage are detected when the option cycle detector is enabled (it’s on by default), but can only be cleaned up if there are no Python-level __del__() methods involved.” So, often Python’s GC does the cleaning up work for you, but sometimes you need to use __del__ as well.. Hope this helps..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: