Python classes and objects :
Python is a “object oriented” programming language. In simple words, classes are templates for the objects , and objects are collection of variables and functions.
Defining classes in python :
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
Python class object Attribute reference :
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
Create a new instance of the class :
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
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
Accessing functions in objects :
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()
Deleting an object in python :
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.