Mastering Python (71 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (30 Blogs)
  • Data Science (39 Blogs)
  • Mastering Python (66 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Object Oriented Programming Python: All you need to know

Published on Jun 25,2019 4.9K Views
1 / 5 Blog from Python OOPs

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Objected oriented programming as a discipline has gained a universal following among developers. Python, an in-demand programming language also follows an object-oriented programming paradigm. It deals with declaring Python classes and objects which lays the foundation of OOPs concepts. This article on “object oriented programming python” will walk you through declaring python classes, instantiating objects from them along with the four methodologies of OOPs. 

In this article, following aspects will be covered in detail:

    Let’s get started.

    INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PYTHON

    Python - Top Programming Languages - Edureka

    Object Oriented Programming is a way of computer programming using the idea of “objects” to represents data and methods. It is also, an approach used for creating neat and reusable code instead of a redundant one. the program is divided into self-contained objects or several mini-programs. Every Individual object represents a different part of the application having its own logic and data to communicate within themselves.

      Now, to get a more clear picture of why we use oops instead of pop, I have listed down the differences below.

      Difference between Object-Oriented and Procedural Oriented Programming

      Object-Oriented Programming (OOP)

      Procedural-Oriented Programming (Pop)

      It is a bottom-up approach

      It is a top-down approach

      Program is divided into objects

      Program is divided into functions

      Makes use of Access modifiers

      ‘public’, private’, protected’

      Doesn’t use Access modifiers

      It is more secure

      It is less secure

      Object can move freely within member functions

      Data can move freely from function to function within programs

      It supports inheritance

      It does not support inheritance

      That was all about the differences, moving ahead let’s get an idea of classes and objects.

      What are Classes and Objects?

      A class is a collection of objects or you can say it is a blueprint of objects defining the common attributes and behavior. Now the question arises, how do you do that?

      Well, it logically groups the data in such a way that code reusability becomes easy. I can give you a real-life example- think of an office going ’employee’ as a class and all the attributes related to it like ’emp_name’, ’emp_age’, ’emp_salary’, ’emp_id’ as the objects in Python. Let us see from the coding perspective that how do you instantiate a class and an object.

      Class is defined under a “Class” Keyword.
      Example:

      class class1(): // class 1 is the name of the class
      

      Note: Python is not case-sensitive.

       Objects:

      Objects are an instance of a class. It is an entity that has state and behavior. In a nutshell, it is an instance of a class that can access the data.

      Syntax: obj = class1()

      Here obj is the “object “ of class1.

      Creating an Object and Class in python:

      Example:

      class employee():
          def __init__(self,name,age,id,salary):   //creating a function
              self.name = name // self is an instance of a class
              self.age = age
              self.salary = salary
              self.id = id
      
      emp1 = employee("harshit",22,1000,1234) //creating objects
      emp2 = employee("arjun",23,2000,2234)
      print(emp1.__dict__)//Prints dictionary
      

      Explanation: ’emp1′ and ’emp2′ are the objects that are instantiated against the class ’employee’.Here, the word (__dict__) is a “dictionary” which prints all the values of object ‘emp1’ against the given parameter (name, age, salary).(__init__) acts like a constructor that is invoked whenever an object is created.

      I hope now you guys won’t face any problem while dealing with ‘classes’ and ‘objects’ in the future.

        With this, let me take you through a ride of Object Oriented Programming methodologies:

        Object-Oriented Programming methodologies:

        Object-Oriented Programming methodologies deal with the following concepts.

        • Inheritance
        • Polymorphism
        • Encapsulation
        • Abstraction

        Let us understand the first concept of inheritance in detail.

        Inheritance:

        Ever heard of this dialogue from relatives “you look exactly like your father/mother” the reason behind this is called ‘inheritance’. From the Programming aspect, It generally means “inheriting or transfer of characteristics from parent to child class without any modification”. The new class is called the derived/child class and the one from which it is derived is called a parent/base class.

        TypesOfInheritance - Python class - Edureka

        Let us understand each of the subtopics in detail.

        Single Inheritance:

        Single level inheritance enables a derived class to inherit characteristics from a single parent class.

        Example:

        class employee1()://This is a parent class
        def __init__(self, name, age, salary):  
        self.name = name
        self.age = age
        self.salary = salary
        
        class childemployee(employee1)://This is a child class
        def __init__(self, name, age, salary,id):
        self.name = name
        self.age = age
        self.salary = salary
        self.id = id
        emp1 = employee1('harshit',22,1000)
        
        print(emp1.age)
        

        Output: 22

        Explanation:

        •  I am taking the parent class and created a constructor (__init__),  class itself is initializing the attributes with parameters(‘name’, ‘age’ and ‘salary’).

        • Created a child class ‘childemployee’ which is inheriting the properties from a parent class and finally instantiated objects ’emp1′ and ’emp2′ against the parameters.

        • Finally, I have printed the age of emp1. Well, you can do a hell lot of things like print the whole dictionary or name or salary.

         

        Multilevel Inheritance:

        Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class.

        Example:

        class employee()://Super class
        def __init__(self,name,age,salary):  
        self.name = name
        self.age = age
        self.salary = salary
        class childemployee1(employee)://First child class
        def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self.salary = salary
        
        class childemployee2(childemployee1)://Second child class
        def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary
        emp1 = employee('harshit',22,1000)
        emp2 = childemployee1('arjun',23,2000)
        
        print(emp1.age)
        print(emp2.age)
        

        Output: 22,23

        Explanation:

        • It is clearly explained in the code written above, Here I have defined the superclass as employee and child class as childemployee1. Now, childemployee1 acts as a parent for childemployee2.

        • I have instantiated two objects ’emp1′ and ’emp2′ where I am  passing the parameters “name”, “age”, “salary” for emp1 from superclass  “employee” and “name”, “age, “salary” and “id” from the parent class “childemployee1”

         

        Hierarchical Inheritance:

        Hierarchical level inheritance enables more than one derived class to inherit properties from a parent class.

        Example:

        class employee():
        def __init__(self, name, age, salary):     //Hierarchical Inheritance
        self.name = name
        self.age = age
        self.salary = salary
        
        class childemployee1(employee):
        def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self.salary = salary
        
        class childemployee2(employee):
        def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary
        emp1 = employee('harshit',22,1000)
        emp2 = employee('arjun',23,2000)
        
        print(emp1.age)
        print(emp2.age)
        

        Output: 22,23

        Explanation:

        • In the above example, you can clearly see there are two child class “childemployee1” and “childemployee2”. They are inheriting functionalities from a common parent class that is “employee”.

        • Objects ’emp1′ and ’emp2′ are instantiated against the parameters ‘name’, ‘age’, ‘salary’.

        Multiple Inheritance:

        Multiple level inheritance enables one derived class to inherit properties from more than one base class.

        Example:

        class employee1()://Parent class
            def __init__(self, name, age, salary):  
                self.name = name
                self.age = age
                self.salary = salary
        
        class employee2()://Parent class
            def __init__(self,name,age,salary,id):
             self.name = name
             self.age = age
             self.salary = salary
             self.id = id
        
        class childemployee(employee1,employee2):
            def __init__(self, name, age, salary,id):
             self.name = name
             self.age = age
             self.salary = salary
             self.id = id
        emp1 = employee1('harshit',22,1000)
        emp2 = employee2('arjun',23,2000,1234)
        
        print(emp1.age)
        print(emp2.id)
        

        Output: 22,1234

        Explanation: In the above example, I have taken two parent class “employee1” and “employee2”.And a child class “childemployee”, which is inheriting both parent class by instantiating the objects ’emp1′ and ’emp2′ against the parameters of parent classes.

        This was all about inheritance, moving ahead in Object-Oriented Programming Python, let’s take a deep dive in ‘polymorphism‘.

        Polymorphism:

        You all must have used GPS for navigating the route, Isn’t it amazing how many different routes you come across for the same destination depending on the traffic, from a programming point of view this is called ‘polymorphism’. It is one such OOP methodology where one task can be performed in several different ways. To put it in simple words, it is a property of an object which allows it to take multiple forms.

         

        Polymorphism Example - Object oriented programming python - Edureka

        Polymorphism is of two types:

        • Compile-time Polymorphism
        • Run-time Polymorphism

        Compile-time Polymorphism:

        A compile-time polymorphism also called as static polymorphism which gets resolved during the compilation time of the program. One common example is “method overloading”. Let me show you a quick example of the same.

        Example:

        class employee1():
        def name(self):
        print("Harshit is his name")    
        def salary(self):
        print("3000 is his salary")
        
        def age(self):
        print("22 is his age")
        
        class employee2():
        def name(self):
        print("Rahul is his name")
        
        def salary(self):
        print("4000 is his salary")
        
        def age(self):
        print("23 is his age")
        
        def func(obj)://Method Overloading
        obj.name()
        obj.salary()
        obj.age()
        
        obj_emp1 = employee1()
        obj_emp2 = employee2()
        
        func(obj_emp1)
        func(obj_emp2)
        

        Output:

        Harshit is his name
        3000 is his salary
        22 is his age
        Rahul is his name
        4000 is his salary
        23 is his age

        Explanation:

        • In the above Program, I have created two classes ’employee1′ and ’employee2′ and created functions for both ‘name’, ‘salary’ and  ‘age’ and printed the value of the same without taking it from the user.

        • Now, welcome to the main part where I have created a function with ‘obj’ as the parameter and calling all the three functions i.e. ‘name’, ‘age’ and ‘salary’.

        • Later, instantiated objects emp_1 and emp_2 against the two classes and simply called the function. Such type is called method overloading which allows a class to have more than one method under the same name.

        Run-time Polymorphism:

        A run-time Polymorphism is also, called as dynamic polymorphism where it gets resolved into the run time. One common example of Run-time polymorphism is “method overriding”. Let me show you through an example for a better understanding.

        Example:

        class employee():
           def __init__(self,name,age,id,salary):  
               self.name = name
               self.age = age
               self.salary = salary
               self.id = id
        def earn(self):
                pass
        
        class childemployee1(employee):
        
           def earn(self)://Run-time polymorphism
              print("no money")
        
        class childemployee2(employee):
        
           def earn(self):
               print("has money")
        
        c = childemployee1
        c.earn(employee)
        d = childemployee2
        d.earn(employee)
        

        Output: no money, has money

        Explanation: In the above example, I have created two classes ‘childemployee1’ and ‘childemployee2’ which are derived from the same base class ‘employee’.Here’s the catch one did not receive money whereas the other one gets. Now the real question is how did this happen? Well, here if you look closely I created an empty function and used Pass ( a statement which is used when you do not want to execute any command or code). Now, Under the two derived classes, I used the same empty function and made use of the print statement as ‘no money’ and ‘has money’.Lastly, created two objects and called the function.

        Moving on to the next Object-Oriented Programming Python methodology, I’ll talk about encapsulation.

        Encapsulation:

        In a raw form, encapsulation basically means binding up of data in a single class. Python does not have any private keyword, unlike Java. A class shouldn’t be directly accessed but be prefixed in an underscore.

        Let me show you an example for a better understanding.

        Example:

        class employee(object):
        def __init__(self):   
        self.name = 1234
        self._age = 1234
        self.__salary = 1234
        
        object1 = employee()
        print(object1.name)
        print(object1._age)
        print(object1.__salary)
        

        Output:

        1234
        Traceback (most recent call last):
        1234
        File “C:/Users/Harshit_Kant/PycharmProjects/test1/venv/encapsu.py”, line 10, in
        print(object1.__salary)
        AttributeError: ’employee’ object has no attribute ‘__salary’

        Explanation: You will get this question what is the underscore and error? Well, python class treats the private variables as(__salary) which can not be accessed directly.

        So, I have made use of the setter method which provides indirect access to them in my next example.

        Example:

        class employee():
        def __init__(self):
        self.__maxearn = 1000000
        def earn(self):
        print("earning is:{}".format(self.__maxearn))
        
        def setmaxearn(self,earn)://setter method used for accesing private class
        self.__maxearn = earn
        
        emp1 = employee()
        emp1.earn()
        
        emp1.__maxearn = 10000
        emp1.earn()
        
        emp1.setmaxearn(10000)
        emp1.earn()
        
        

        Output:

        earning is:1000000,earning is:1000000,earning is:10000

        Explanation: Making Use of the setter method provides indirect access to the private class method. Here I have defined a class employee and used a (__maxearn) which is the setter method used here to store the maximum earning of the employee, and a setter function setmaxearn() which is taking price as the parameter.

        This is a clear example of encapsulation where we are restricting the access to private class method and then use the setter method to grant access.

        Next up in object-oriented programming python methodology talks about one of the key concepts called abstraction.

        Abstraction:

         

        bookmyshow - Object Oriented programming Python - EdurekaSuppose you booked a movie ticket from bookmyshow using net banking or any other process. You don’t know the procedure of how the pin is generated or how the verification is done. This is called ‘abstraction’ from the programming aspect, it basically means you only show the implementation details of a particular process and hide the details from the user. It is used to simplify complex problems by modeling classes appropriate to the problem.

        An abstract class cannot be instantiated which simply means you cannot create objects for this type of class. It can only be used for inheriting the functionalities.

        Example:

        from abc import ABC,abstractmethod
        class employee(ABC):
        def emp_id(self,id,name,age,salary):    //Abstraction
        pass
        
        class childemployee1(employee):
        def emp_id(self,id):
        print("emp_id is 12345")
        
        emp1 = childemployee1()
        emp1.emp_id(id)
        
        

        Output: emp_id is 12345

        Explanation: As you can see in the above example, we have imported an abstract method and the rest of the program has a parent and a derived class. An object is instantiated for the ‘childemployee’ base class and functionality of abstract is being used.

        This brings us to the end of our article on “Object-Oriented Programming Python”. I hope you have cleared with all the concepts related to Python class, objects and object-oriented concepts in python. Make sure you practice as much as possible and revert your experience.

        Got a question for us? Please mention it in the comments section of this “Object Oriented Programming Python” blog and we will get back to you as soon as possible. To get in-depth knowledge of Python along with its various applications, you can enroll here with our live online training with 24/7 support and lifetime access.

        Comments
        0 Comments

        Browse Categories

        webinar REGISTER FOR FREE WEBINAR
        REGISTER NOW
        webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

        Subscribe to our Newsletter, and get personalized recommendations.