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)
 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.
>>> employee2.getTotalSumForLeaveBalance()
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


  1. Replies
    1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

      Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

      Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

      The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

  2. This comment has been removed by the author.

  3. 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

  4. 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

  5. Great efforts put to publish these kinds of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create great relations. You’re doing an excellent job. Keep it up.

    Magento Development Training Course in Chennai Zuan Education

    Selenium Training Course in Chennai Zuan Education

  6. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man learn Python Online Course

  7. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man learn Python Online Course

  8. Enjoyed reading the article above, really explains everything in detail, the article is very interesting and effective. Thank you and good luck for the upcoming articles Python certification

  9. tableau online training
    tableau online course
    tableau training

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

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

Previous Post Next Post