What are Python OOP Basics?



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.


Advertisements