Simple Object Oriented Program in Python

# Python Program to understand Classes

class base:
    def __init__(self,var):
        self.var = var
        print "Object Initiated"
    def printVar(self):
        print self.var
object = base("FirstObject")
object.printVar()

'''
First Line is definition of class named base,

In the world of Object Oriented Programming,a class means a datatype
which user can define.

second line is a Constructor, which is the function that gets executed
when an object of that class is created,

The need of constructor is basically to allocate the memory required to
newly created object.
There is no memory leaks in Python, so we dont have any destructors here.

I will explain this line : def __init__(self,var):
then name of constructor must be __init__,

self is like this pointer in C++, which points to the class itself,
each function in class will have one common argument : self
self.var = var will assign passed variable var to base's internal variable
self.var,

in second function printVar we are not passing any arguments but still self will remain.
now we already have base's own variable self.var defined in constructor __init__,we
can use it in printVar.

finally an object called "object" is created of type base,
and function printVar is called through object.printVar()

'''

No comments: