Sunday, April 8, 2012

Constructors

Hello everyone, in this post I will discuss something about Class.

So far, we know almost the basics of how to use a Class and how to make an object and how to use them.

But most of the time, it is required to do something automatically, as soon as the object is created, We will go in details about the usage in our later posts, as of now, we have to know how to make it and remember it, so that when we use it in making scripts we don't get confused.

This is the concept of an inbuilt python method known as constructor. So when a constructor method is created inside a class, and then when an object is created to use the class, Python looks if there is any constructor in the class, if it finds one, it automatically executes the constructor.

NOTE: This is the difference, previously when we used a method, we had to call the method from the class with a DOT Operator. But for a Constructor, we don't have to do so, as it automatically executes the constructor.


The built method for defining a Constructor is: def __init__(self): [Anything in this method is automatically executed and its a double underscore

Lets check a small example:

>>> class Test:
            var = "This is just a Variable"
            def __init__(self):
                     print "I Got executed even before I was called"
            def callMe(self):
                     print "I Am Lazy, You have to Call Me to See Me"

       
>>> ObjectTest = Test()
I Got executed even before I was called
>>> ObjectTest.var
'This is just a Variable'
>>> ObjectTest.callMe()
I Am Lazy, You have to Call Me to See Me
>>>

So I Hope Makes Everything Clear about what A Constructor is.

Practice it, and Don't forget to check my next Post.

Thank You.

0 comments:

Post a Comment