Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Python OOPS Concept
2.1.
Class
2.2.
Object
2.3.
Creating a class and objects
2.4.
Creating Methods in Python
2.5.
Inheritance
2.5.1.
Single Inheritance
2.5.2.
Multi-level  inheritance
2.5.3.
Multiple inheritance
2.5.4.
Multipath inheritance
2.5.5.
Hybrid inheritance
2.5.6.
Hierarchical Inheritance
2.6.
Encapsulation
2.7.
Polymorphism
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Object-Oriented Programming Python

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In the programming world, the Python language has attracted a lot of mass due to its English-like syntax and portable nature.
Variables play an essential role in any programming language; they occupy memory to store the data for further use in the program.
In Python, object-oriented programming(oops) uses class and objects. This helps to solve real-world problems in programming. 

This article will walk you through declaring python classes, instantiating objects from them, along with the four methodologies of OOPs.

 

image

Source: coding geek

What is object-oriented programming?
Oops is a computer programming language using data or objects to represent data and methods. It is used to remove the redundancy of data. 

Must Recommended Topic, Floor Division in Python and Convert String to List Python.

Python OOPS Concept

Python oops concept includes Class, Object, Method, Inheritance, Polymorphism, Data Abstraction, and Encapsulation.

Class

A class is a collection of objects or a blueprint for the objects. It is a logical entity that contains some attributes and methods. For example, if there are many cars, and you want to distinguish them, how will you distinguish them? We have different attributes like colour model; If a list is used, the first element can be the car's model, and the second element could be the colour. What if there are 1000 different cars? You need to add other properties to these cars for recognization. For this we need classes.

The syntax for defining a class:

class ClassName:

            <S-1>

            .

            .

            .

            <S-N>

Note: 

  • Classes are created or declared by keyword class.
  • From class, we construct instances. An instance is a specific object created from a particular class.

Object

An object/ instance is an instantiation of a class. The object is an entity with behaviour and state and its two characteristics.

For example, A pencil is an object, and it has the following properties:
attributes: thickness, type.
behavior: Writing, drawing.

Creating an object
obj = pencil()

This will create an object of the name obj of the class pencil.

The first image (A) represents a house blueprint considered a Class. With the same blueprint of the house, we can create several houses regarded as objects.

Also see, Python Filter Function

Creating a class and objects

Before diving into creating the objects and classes, one should be clear about some basic keywords used in the future.

The init method will run as soon as the class is instantiated, just like constructors in C++ and Java. When we write a method inside a class, they receive instances automatically. 

The self method represents the instance of the class. By using the 'self' keyword, we can access the attributes and methods of the class in Python.

Example

class student:  
    def __init__(self,name, age):  
       self.name = name 
        self.age = age 
    def display(self):  
        print(self.name,self.age)  
  
s1= student("Sarthak", 20)  
s1.display()  

Output

Sarthak 20

 

Know What is Object in OOPs here in detail.

Creating Methods in Python

Methods are defined inside the body of a class. In Python, a method is not unique to class instances.

class Student:
    
    # instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # instance method
    def eat(self, act):
        return "{} eats {}".format(self.name, act)

    def happy(self):
        return "{} is now eating".format(self.name)

# instantiate the object
perk= Student("Perk", 10)

# call our instance methods
print(perk.eat("'Banana'"))
print(perk.happy())

Output

Perk eats ‘Banana’
Perk is now eating


There are two methods in the above example, i.e., eat() and happy(). These are called instance methods.

Inheritance

Inheritance is an OOPs methodology that allows us to define a class that inherits all the methods and properties from another class. It provides the reusability of the code.

  • The parent class is inherited from the base class.
  • The child class is the class that inherits properties from another class, i.e., the base class, also called the derived class.

Example

# parent class
class Manager(object):
 
	# __init__ is known as the constructor
	def __init__(self, name, id_num):
		self.name = name
		self.id_num = id_num
 
	def display(self):
		print(self.name)
		print(self.id_num)

	def details(self):
		print("My name is {}".format(self.name))
		print("The id number is: {}".format(self.id_num))

# child class
class Employee(Manager):
	def __init__(self, name, id_num, salary):
		self.salary = salary
 
		Manager.__init__(self, name, id_num)

	def details(self):
		print("My name is {}".format(self.name))
		print("The id number is: {}".format(self.id_num))
 
 
# creation of an instance
c = Employee('Sarthak', 456777, 500000)
c.display()
c.details()

Output

Sarthak
456777
My name is Sarthak
The id number is: 456777


You can practice by yourself with the help of online python compiler.

As per the above example, we have created two classes, i.e., Manager and Employee, and the parent and child classes, respectively. We can use the methods of the Manager class through the employee class as the employee class inherits from the manager class. 

There are Five types of inheritance as follows:

image

                                                                                                            Source: techvidvan

 

Single Inheritance

This inheritance creates a derived class(child class) from a single base class(parent class).

Class A is the parent class in the given an example below, and Class B is the child class.

Single inheritance

Source: dotnettricks

 

Multi-level  inheritance

In this inheritance, a derived class(child class) is created from another derived class.

multilevel inheritance

In the above example, where A is the parent class of B, class B is the parent class of C, as class C inherits the properties of class B, and class B inherits the properties of class A.

Know about Single Inheritance in Java in detail.

Multiple inheritance

In this inheritance, a derived class(child class) is created from more than one base class(parent class). .NET Languages like C#, F#, and Java do not support this inheritance.

multiple inheritance

Here, A and Class B are both the parent classes for Class C.

Multipath inheritance

Over here, a derived class is created from other derived classes and the same base class of another derived class.

multipath inheritance

Class A is the parent for Class B and Class C, as well as Class D.

Hybrid inheritance

This is the combination of more than one inheritance. Hence, it may be a combination of Multilevel and Multiple inheritance or Hierarchical and Multilevel inheritance or Hierarchical and Multipath inheritance or Hierarchical, Multilevel and Multiple inheritance.

hybrid inheritance


Hierarchical Inheritance

In this inheritance, more than one derived class is created from a single base class, and further child classes act as parent classes for more than one child class.

hierarchical inheritance

For more details, refer to our Inheritance in Python tutorial.

Encapsulation

Simply, encapsulation is a binding up of data in a single class as it is used to restrict access to methods and variables. In Python, private attributes are denoted using underscore as the prefix, i.e., single _ or double __.

An example of encapsulation is a class as it encapsulates all the data, member functions, variables, etc.

Example

# Parent class
class parent:
	def __init__(self):
		self.d = "Coding"
		self.__s = "Ninjas"

# Child class
class child(parent):
	def __init__(self):

		parent.__init__(self)
		print("Calling the member of parent class: ")
		print(self.__s)

obj1 = parent()
print(obj1.d)

Output

Coding


As per the above example, we have created the s variable as the private attribute. We cannot even access this attribute directly and can't change its value.

Also see, Merge Sort Python

Polymorphism

The polymorphism is one such OOP methodology where one task can be performed in several ways. For example, you have an animal class, and all animals speak. But they speak differently. So by using polymorphism, we can do this using a single function.

Example

class Animal:

	def main(self):
		print("Variety of Animals.")

	def walk(self):
		print("Some animals are slow while some have fast speed.")

class Elephant(Animal):

	def eat(self):
		print("Elephant is vegetarian.")

class Tiger(Animal):

	def eat(self):
		print("Tiger is a non-vegetarian.")

obj_animal = Animal()
obj_ele = Elephant()
obj_tiger = Tiger()

obj_animal.main()
obj_animal.walk()

obj_ele.main()
obj_ele.eat()

obj_tiger.main()
obj_tiger.eat()

Output

Variety of Animals.
Some animals are slow, while some have fast speed.
Variety of Animals.
Elephant is vegetarian.
Variety of Animals.
Tiger is a non-vegetarian.

Check out this article - Compile Time Polymorphism.

Must Read Invalid Syntax in Python.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

  1. What is the difference between object-oriented and procedural programming?
    Object-oriented programming:
    It is a problem-solving approach used where computation is done by using objects.
    Example of object-oriented programming languages is Java, C++, .Net, Python, etc.
    Procedural programming:
    It uses a list of instructions to do computation step by step.
    Examples of procedural languages are C, Fortran, Pascal, VB, etc.
     
  2. What do you mean by data abstraction?
    Abstraction is used to hide the internal functionality of a program from the users.

Key Takeaways

This blog has covered the following topics:
What do you mean by objected-oriented programming? What are the different oops concepts in Python? Implementation of class, object, encapsulation, polymorphism, inheritance, etc.

Recommended Readings: 

 

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Happy Coding!!!

Previous article
How everything in Python is an Object?
Next article
Polymorphism in Python
Live masterclass