Object oriented programming in python - Class and Object

Python support object oriented programming paradigm along with procedural programming. Classes and Objects are the two important aspects of object oriented programming. A class creates a new type (analogous to an int class of python) and objects are instances of the class.

Object uses variables to store data called instance variables. variables can also be created in class context, those variables are called Class variables. Variables(fields) and methods are attributes of class.
Along with variables, class also contain methods. In OOP terminology , instance variables are also known as data members and  methods are also
known as member functions.
Class is created using keyword class and fields, methods are added in indented block.A sample class can be created like this.We will see in detail about object included in Employee class while dealing with inheritance in python.
class Employee(object): #object class is mother of all class in python
 # Class variable declaration  
 ......
 # Constructor of class - init() methods
 .......
 # class methods - self identifier  
 ........
self identifier and __init__():- Before going delve into actual class creation, let's understand importance of self and init() in python.
  • It is the self identifier which differentiate class methods from normal python functions. It is mandatory to include self as first parameter list in class methods(member function).self identifies the instance upon which a method is invoked.Please note that, instead of "self" we can use any other name as first parameter in class method, however it is highly recommended to use "self" for the same. When we call any method in object context, we do not pass any thing for self parameter, python handle internally it and pass object reference to it.
  • __init__() method in python serves as constructor as in other language for creating instance of class.When an instance of class is created then python internally execute __int__() method and initialize member fields(instance variables).
Lets create an Employee class with fields - name, employeeId , position and leaveBalance, getters corresponding to these fields and member functions for allocateLeave and sum accumulated corresponding to leave balance.Open Pyhton IDLE and create a new file and copy below sample code in it.
     
class Employee(object):
 '''class variables'''
 _basicSum = 1500
 _allowance = 1000 
 '''Create a new Employee instance with 
    default value of leave balance 0'''
 def __init__ (self, _name,_employeeId, _position):
   self._name = _name
   self._employeeId = _employeeId
   self._position = _position
   self._leaveBalance = 0 #Default value 0
 """getter method for member fields"""
 def get_name(self):
   return self._name
 def get_employeeId(self):
   return self._employeeId
 def get_position(self):
   return self._position
 def get_leaveBalance(self):
   return self._leaveBalance
 '''member function to return sum accumulated  
    corresponding for leave balance'''
 def getTotalSumForLeaveBalance(self):
   return (self._leaveBalance * Employee._basicSum)
   +(Employee._allowance*self._leaveBalance)
 def allocateLeave(self,_leaveBalance):
   self._leaveBalance =  _leaveBalance
Lets walk through the code lines of above class: _basicSum and _allowance are class variables (shared by all instance of class). After that __init__ (self, _name,_employeeId, _position) is defined with first parameter self and other three are instance members. When we create instance of Employee this _init_(...) is executed automatically and member variables are initialized with value passed and default value 0 for _leaveBalance.We have getter method for these member variables and followed by two member function to allocate leave and calculateSum corresponding for leave. We can spot that self is used to access member variables corresponding to the object and class variables is accessed via class name as it is carries in other language  like java. 

Now we will following operation in sequence : 1. create instance of Employee class  2. Allocate leave to new Employee instance. 3.Calculate sum total for leaveBalance.
Create instance of Employee class like this in python terminal :
>>> employee1 = Employee('Nikhil',007,'SSE')   # employee1 reference an instance of Employee
>>> employee2 = Employee('Ranjan',99,'TL')     # employee2 reference an instance of Employee

Allocate leave to both(employee1 and employee2) Employee instance like this: 
.>>> employee1.allocateLeave(12)  # 12 leaves assigned to employee1
>>> employee2.allocateLeave(15)   # 15 leaves assigned to employee2

Calculate sum total for these two instances: 
>>> employee1.getTotalSumForLeaveBalance()  #No value passed for self ,python does it implicitly.
18000
>>> employee2.getTotalSumForLeaveBalance()
22500
Above sequence of events for instance employee1 can be summarized by sequence diagram:

Sequence diagram for creating employee1 instance and calculating sum total
Few point worth noting about class and objects :
  • Every object refers to it’s class via the self.__class__ attribute. So, instead of accessing class variable like Employee._basicSum , we can use self.__class__._basicSum.
  • __class__ is a built-in attribute of every class instance. It is a reference to the class that self is an instance of.
  • All class members (including the data members) are public and all the methods are virtual in Python.
  • Private name mangling: When an identifier in class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class.

Sample example using class and Object:-  



Previous: Iterators and Generators in python Next : Method overloading and Operator overloading

11 Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    mobile application development training online
    web designing and development course training institute in Chennai with placement

    ReplyDelete
  3. really love the theme/design of your website. Do you ever run into any browser compatibility problems? A small number of my blog audience have complained about my site not working correctly in Explorer but looks great in Safari. Do you have any ideas to help fix this problem?
    Surya Informatics

    ReplyDelete
  4. tableau online training
    tableau online course
    tableau training

    ReplyDelete
  5. Nice informative content. Thanks for sharing the valuable information.
    Node Js Development
    Node Js Framework

    ReplyDelete
  6. Thank you ever so for you blog article. Thanks Again. Cool.
    best digital learning

    ReplyDelete
Previous Post Next Post