Python is known as an object-oriented language. Its open-source and high-level coding have enabled programmers to create and use classes and objects effortlessly. This chapter assists you to become proficient in utilizing Python's object-oriented programming support.
However, we are introducing small details about Object-Oriented Programming (OOP)-
The class statement develops a new class of account. The name of the class right away adhere the keyword class followed by a colon as follows:
class ClassName: 'Optional class documentation string' class_suite
Example
Following is the example of a simple Python class:
class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary
To form instances of a class, users need to call the class name and pass __init__ method accepts.
"This would create first object of Employee class" emp1 = Employee("Mack", 2000) "This would create second object of Employee class" emp2 = Employee("Sunni", 5000)
Users access the object's attributes through the dot operator with object utilization. A class variable is acquired through class name as follows
emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
Now, putting all the concepts together:
#!/usr/bin/python class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary "This would create first object of Employee class" emp1 = Employee("Mack", 2000) "This would create second object of Employee class" emp2 = Employee("Sunni", 5000) emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
When the above code is executed, it produces the following result
Name : Mack ,Salary: 2000 Name : Sunni ,Salary: 5000 Total Employee 2
You can add, remove, or modify attributes of classes and objects at any time:
emp1.age = 7 # Add an 'age' attribute. emp1.age = 8 # Modify 'age' attribute. del emp1.age # Delete 'age' attribute.
Rather than utilizing the normal statements to right of entry attributes, users can use these functions-
hasattr(emp1, 'age') # Returns true if 'age' attribute exists getattr(emp1, 'age') # Returns value of 'age' attribute setattr(emp1, 'age', 8) # Set attribute 'age' at 8 delattr(empl, 'age') # Delete attribute 'age'
Every Python class rolls out the provided built-in attributes. These attributes can be accessed through dot operator similar to any other attribute-
For the above class let us try to access all these attributes-
#!/usr/bin/python class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary print "Employee.__doc__:", Employee.__doc__ print "Employee.__name__:", Employee.__name__ print "Employee.__module__:", Employee.__module__ print "Employee.__bases__:", Employee.__bases__ print "Employee.__dict__:", Employee.__dict__
When the above code is executed, it produces the following result:
Employee.__doc__: Common base class for all employees Employee.__name__: Employee Employee.__module__: __main__ Employee.__bases__: () Employee.__dict__: {'__module__': '__main__', 'displayCount': , 'empCount': 2, 'displayEmployee': , '__doc__': 'Common base class for all employees', '__init__': }
You usually will never become aware of it whilst the garbage collector wipes out an orphaned instance and retrieves its space. Excluding a class can apply the special method __del__(), called a destructor, that is incorporate when the example is about to be destroyed. This technique is used to onslaught any non-memory reserves applied by an instance.
This __del__() destructor prints the class name of an instance that is about to be destroyed-
#!/usr/bin/python class Point: def __init__( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print class_name, "destroyed" pt1 = Point() pt2 = pt1 pt3 = pt1 print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts del pt1 del pt2 del pt3
When the above code is executed, it produces the following result:
#!/usr/bin/python class Point: def __init__( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print class_name, "destroyed" pt1 = Point() pt2 = pt1 pt3 = pt1 print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts del pt1 del pt2 del pt3
Note - preferably, users ought to describe the classes in different files. Users may import these files in the main program file utilizing the command import statement.
Instead of beginning from scrape, users could create a class by deriving inheritance from a pre-existed class by Tuple the component class in parentheses. after the new class name. The child class inherits the attributes of its parent class. Users can employ those attributes if they have defined them in the child class. Keep in mind, a child class can supersede data members and methods while inheriting from the parent.
Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name-
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
#!/usr/bin/python class Parent: # define parent class parentAttr = 100 def __init__(self): print "Calling parent constructor" def parentMethod(self): print 'Calling parent method' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "Parent attribute :", Parent.parentAttr class Child(Parent): # define child class def __init__(self): print "Calling child constructor" def childMethod(self): print 'Calling child method' c = Child() # instance of child c.childMethod() # child calls its method c.parentMethod() # calls parent's method c.setAttr(200) # again call parent's method c.getAttr() # again call parent's method
When the above code is executed, it produces the following result:
Calling child constructor Calling child method Calling parent method Parent attribute : 200
Similar way, you can drive a class from multiple parent classes as follows:
class A: # define your class A ..... class B: # define your class B ..... class C(A, B): # subclass of A and B .....
You can use issubclass() or isinstance() functions to check the relationships of two classes and instances.
Users could always take priority over the parent class techniques. One of the reasons for superseding the parent's methodology is the preference for special or different functionality in a subclass.
#!/usr/bin/python class Parent: # define parent class def myMethod(self): print 'Calling parent method' class Child(Parent): # define child class def myMethod(self): print 'Calling child method' c = Child() # instance of child c.myMethod() # child calls overridden method
When the above code is executed, it produces the following result:
Calling child method
Following table lists some generic functionality that you can override in your own classes
Sr.No. | Method, Description & Sample Call |
1 | __init__ ( self [,args...] ) Constructor (with any optional arguments) Sample Call : obj = className(args) |
2 | __del__( self ) Destructor, deletes an object Sample Call : del obj |
3 | __repr__( self ) Evaluable string representation Sample Call : repr(obj) |
4 | __str__( self ) Printable string representation Sample Call : str(obj) |
5 | __cmp__ ( self, x ) Object comparison Sample Call : cmp(obj, x) |
Presume that users have developed a Vector class to depict two-dimensional vectors. As a result, users apply the plus operator to put in the class. However, the programming language notifies users about it.
You could, however, define the __add__ method in your class to perform vector addition, and then the plus operator would behave as per expectation-
#!/usr/bin/python class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 + v2
When the above code is executed, it produces the following result:
Vector(7,8)
An object's attributes perhaps stay noticeable outside the class definition. Users are required to name attributes providing a double underscore prefix. Mostly, these attributes are not directly observable to outsiders.
#!/usr/bin/python class JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.__secretCount
When the above code is executed, it produces the following result:
1 2 2
Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.