Object Oriented Programming Python: All you need to know

Last updated on Jul 05,2024 148.9K Views

Object Oriented Programming Python: All you need to know

edureka.co

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.

What is Object-Oriented Programming? (OOPs concepts in Python)

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 Python OOPs Conceots.

What are Python OOPs Concepts?

Major OOP (object-oriented programming) concepts in Python include Class, Object, Method, Inheritance, Polymorphism, Data Abstraction, and Encapsulation.

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 which are further covered under our Python Course

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.

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:

 

 

This video talks about the Top 10 Trending Technologies in 2024 that you must learn.

 

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:

 

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:

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 is of two types:

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:

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:

 

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

Is Python 100 percent object oriented?

Python doesn’t have access specifiers like “private” as in java. It supports most of the terms associated with “objected-oriented” programming language except strong encapsulation. Hence it is not fully object oriented.

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. Also Checkout this OOPs Interview Questions and Answers that helps you to practice for job interview.

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 now with Edureka‘s live Python course training with 24/7 support and lifetime access.

Discover your full abilities in becoming an AI and ML professional through our Artificial Intelligence Course. Learn about various AI-related technologies like Machine Learning, Deep Learning, Computer Vision, Natural Language Processing, Speech Recognition, and Reinforcement learning.

Upcoming Batches For Data Science with Python Certification Course
Course NameDateDetails
Data Science with Python Certification Course

Class Starts on 14th December,2024

14th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Time Series Analysis using Python