The Python programming paradigm known as object-oriented programming (OOPs) makes use of objects and classes. It seeks to incorporate in programming real-world concepts like inheritance, polymorphism, encapsulation, etc. The fundamental idea behind OOPs is to bind the data and the functions that use it such that no other part of the code could access it.
In this article we will discuss about the fundamental principles of object-oriented programming.
Class
The definition of a class is a group of items. It is a logical entity with a few unique attributes and methods. For instance, if you have a class for Cricket, it should have an attribute and method like players, tournaments, toss, runs, wickets, matches, etc.
Example
Consider using the example below to construct a class called Cricket that has two fields: player id and player.The class also has a function called display() that is used to show Cricket information â
class Cricket:
id = 10
player = âSachin Tendulkarâ
def display (self):
print(self.id,self.player)
print(âClass created Successfullyâ)
Output
Following is an output of the above code
Class created Successfully
Object
An object is an instance of a class. It is an entity with state and behaviour. Simply said, it is a class instance that has access to the data.It could be any real-world object, such as a mouse, keyboard, chair, table, pen, etc.
Python treats everything as an object, and most objects have attributes and methods. The built-in attribute doc of all functions returns the docstring specified in the functionâs source code.
Example
Following is an example to create an object â
class Cricket:
id = 10
player = âSachin Tendulkarâ
def display (self):
print(âID: %d \nPlayer: %sâ%(self.id,self.player))
Create crkt instance of Cricket class
crkt = Cricket()
crkt.display()
Output
Following is an output of the above code:
ID: 10
Player: Sachin Tendulkar
Method
A function connected to an object is the method. A method is not specific to class instances in Python. Any sort of object may have methods.
Example
In the following example two methods, plant() and animals(), are defined. Because âPenâ is an instance object, these are known as instance methods.
class Program:
The instance attributes
def init(self, name, age):
self.name = name
self.age = age
The instance method
def plant(self, eucalyptus):
return â{} plants {}â.format(self.name, eucalyptus)
def animals(self):
return â{} animalsâ.format(self.name)
instantiating the object
Pen = Program(âPenâ, 10)
calling the instance methods
print(Pen.plant(ââCodingââ))
print(Pen.animals())
Output
Following is an output of the above code â
Pen plants âCodingâ
Pen animals
Inheritance
By utilising the details of an existing class without changing it, a new class can be created through inheritance. The newly created class is a derived class (or child class). The existing class is a base class(or parent class) in a similar way.
Example
Following is an example of inheritance in Python
The parent class
class Animal:
def init(self):
print(âAnimal is thereâ)
def WhatIstheClass(self):
print(âAnimalâ)
def Run(self):
print(âRuns in speedâ)
The child class
class Lion(Animal):
def init(self):
# call super() function
super().init()
print(âLion is thereâ)
def WhatIstheClass(self):
print(âLionâ)
def run(self):
print(âRuns in speedâ)
blu = Lion()
blu.WhatIstheClass()
blu.Run()
blu.run()
Output
We established two classes in the above code: Animal (parent class) and Lion(child class). The parent classâs functions are inherited by the child class. This is evident from the Run() method.
Again, the behaviour of the parent class was modified by the child class. The WhatIstheClass() method reveals this. By adding a new run() method, we also expand the parent classâs functionality.
In the init() method, we also use the super() function. This enables us to call the parent classâs init() method from the child class.
Animal is there
Lion is there
Lion
Runs in speed
Runs in speed
Encapsulation
We can limit access to methods and variables in Python by using OOP. Encapsulation is the process of preventing direct data modification. In Python, we use the underscore prefix to indicate private attributes, such as single_or double__.
Example
Following is an example of data encapsulation in Python â
class Sports:
def init(self):
self.__sportsName = âCricketâ
def game(self):
print(âThe game is: {}â.format(self.__sportsName))
def Player_Name(self, player):
self.__sportsName = player
s = Sports()
s.game()
changing the sports name
s.__sportsName = âHockeyâ
s.game()
using the setter function
s.Player_Name(âHockeyâ)
s.game()
Output
The Sports class is defined in the code above. The game name of Sports is stored using the init() method. Look at the code below
s.__sportsName = âHockeyâ
Here, weâve attempted to change the __sportsName value outside of the class. Since __sportsName is a private variable, the output does not reflect this modification. We must utilise a setter function, Player Name(), which accepts sportsName as the parameter, in order to adjust the value.
The game is: Cricket
The game is: Cricket
The game is: Hockey
Polymorphism
âPolyâ and âmorphsâ are two words that make up polymorphism. The words poly and morp means many and shape respectively. We understand polymorphism to mean that a single activity can be carried out in various ways.
Letâs say we want to colour a shape; we have a variety of shape choices (square, pentagon, circle). However, we could colour any shape using the same method. This concept is known as polymorphism.
Example
Following is an example of Polymorphism in Python
class Lion:
def Roar(self):
print(âLion can roarâ)
def Bark(self):
print(âLion canât barkâ)
class Dog:
def Roar(self):
print(âDog canât roarâ)
def Bark(self):
print(âDog can barkâ)
same qualities
def sound_test(mammal):
mammal.Roar()
#instantiate objects
pet = Lion()
street = Dog()
passing the object
sound_test(pet)
sound_test(street)
Output
Two classes, Lion and Dog, were defined in the above code. They all share the Roar() method. Their roles, however, are distinct.
To utilize polymorphism, we built a common interface called sound test(), which accepts any object and calls its Roar() method. As a result, the sound test() function worked as expected when we passed the pet and street objects to it.
Lion can roar
Dog canât roar
Data Abstraction
Both data abstraction and encapsulation are frequently used synonyms. Since data abstraction is achieved by encapsulation, the two terms are almost synonymous.
When using abstraction, internal details are hidden and only functionalities are displayed. Giving things names that capture the core of what a function or an entire program does is the process of abstracting something.