Python is a “object oriented” programming language. In simple words, classes are templates for the objects , and objects are collection of variables and functions.
Class definition looks like :
class ClassName : statements
Similar to functions, class definitions should execute at first before running. We can also add one string at the first line of the class with a brief description about the class. This is known as docstring.
class ClassName : ‘’’This is a sample docstring…’'' statements
While creating a new class , python automatically creates one object with that class name. We can access any class member using dot(.) with the class name :
class DummyClass : ''' This is a dummy class ''' i = 10 print DummyClass.i
It will print 10 . This is known as “Attribute Reference” in python. We can also change the value of “i” using assigning. Add the following two lines at the bottom and it will print “11” on running again :
DummyClass.i = 11 print DummyClass.i
Let’s create one new instance of the above class :
class DummyClass : ''' This is a dummy class ''' i = 10 myClass = DummyClass() print myClass.i
In the above example, we have created a new instance of the class DummyClass and assign it to variable myClass . It will create an empty object myClass . If you want to change the parameter value’s of a newly created object, one new method init( ) ** should be implemented inside it. **init( ) is called first when creating new instance of a class.
class DummyClass : ''' This is a dummy class ''' i = 10 def __init__(self,newval): self.i = newval myClass = DummyClass(11) print myClass.i
Here, we are passing an argument 11 while instantiating class DummyClass, so it will give 11 as output on the print statement .
Accessing functions inside a object is same as accessing variables, i.e. we can access by using a dot ( . ) operator :
class DummyClass : ''' This is a dummy class ''' i = 10 def __init__(self,newval): self.i = newval def myfunc(self): print ("value of i is = %d "%(self.i)) myClass = DummyClass(11) myClass.myfunc()
Python has one garbage collector. It runs periodically and deletes unused objects automatically and free up memory space if an object is not referencing by anything. We can also manually delete an object using del Let’s make some changes to the above example :
class DummyClass : ''' This is a dummy class ''' i = 10 def __init__(self,newval): self.i = newval def myfunc(self): print ("value of i is = %d "%(self.i)) myClass = DummyClass(11) del myClass myClass.myfunc()
Traceback (most recent call last): File “filename.py", line 14, in myClass.myfunc() NameError: name 'myClass' is not defined
as we have deleted the myClass object, it has thrown an error that this object is not defined.