OOPs Python

OOPs (Object Oriented Programming) in Python

OOPs (Object Oriented Programming) in Python

Introduction

Objects and classes are used in the object-oriented programming (OOPs) paradigm of the Python programming language. It aims to include programming notions from the real world, such as polymorphism, encapsulation, and inheritance. Binding the data and the functions that use it so that no other portion of the code may access them is the core concept underpinning OOPs. We'll talk about the fundamentals of object-oriented programming in this post.

Class

A class is a collection of things, according to definition. It is a rational being with a few distinctive qualities and techniques. For instance, a class for cricket should include methods and attributes for players, competitions, tosses, runs, wickets, and matches, among other things.

Example

Consider creating a class named Cricket with two fields: player id and player, as seen in the example below. Additionally, the class provides a method named display() that displays Cricket-related data.

class Cricket:
    id = 10
    player = "Number #1"
    def display (self):
        print(self.id,self.player)
    print('Class created Successfully')

Output:

Class created Successfully

Object

A class's instances are objects. It is a living being having a state and actions. It is a class instance, to put it simply, that has access to the data. Any physical device, including a mouse, keyboard, chair, table, pen, etc., might be used. The majority of objects contain attributes and functions because Python sees everything as an object. The docstring given in the function's source code is returned by the built-in attribute __doc__ of all functions.

Example

Following is an example to create an object −
class Cricket:
  id = 10
  player = "Number #1"
  def display (self):
      print("ID: %d \nPlayer: %s"%(self.id,self.player))
crkt = Cricket()
crkt.display()

Output:

ID: 10
Player: Number #1

Method

The method is a function associated with an object. In Python, a method is independent of class instances. Methods may be found in any kind of object.

Example

Two methods, plants() and animals(), are specified in the example below. These are referred to as instance methods since "Pen" is an instance object.

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:

Pen plants 'Coding'
Pen animals

Inheritance

Through inheritance, a new class may be made by using the specifics of an existing one without altering it. A derived class has just been created (or child class). In a similar manner, the existing class is a base class or parent class.

Example

Here is an illustration 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:

Animal (parent class) and Lion are the two classes we established in the aforementioned code (child class). The child class inherits the parent class's functionalities. The Run() function clearly shows this. Once more, the kid class altered the parent class's behavior. This is made clear via the WhatIstheClass() function. We also increase the functionality of the parent class by including a new run() method. The super() function is also used in the __init__() method. This gives us the ability to invoke the __init__() function of the parent class from the child class.

Animal is there
Lion is there
Lion
Runs in speed
Runs in speed

Encapsulation

Using OOP, we may restrict access to Python methods and variables. The method of preventing direct data alteration is called encapsulation. In Python, private properties like single and double are denoted by the underscore prefix.

Example

Here is an illustration of Python data encapsulation:

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()
s.__sportsName = 'Hockey'
s.game()
s.Player_Name('Hockey')
s.game()

Output:

The code above defines the Sports class. The __init__() function is used to save the game's name in Sports. View the code below.

s.__sportsName = 'Hockey'

Here, outside of the class, we've tried to alter the __sportsName value. Because __sportsName is a private variable, this adjustment is not reflected in the output. To change the value, we must use the setter method Player Name(), which takes sportsName as an argument.

The game is: Cricket
The game is: Cricket
The game is: Hockey

Polymorphism

Polymorphism is made of the terms "poly" and "morphs." Poly and morp, which stand for many and form, respectively. We define polymorphism as the ability to do a single action in a variety of ways. Let's imagine we wish to color a form; there are many different shape options available (square, pentagon, circle). However, we could use the same technique to color any form. This idea is referred to as polymorphism.

Example

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")
def sound_test(mammal):
  mammal.Roar()
pet = Lion()
street = Dog()
sound_test(pet)
sound_test(street)

Output:

The code above defined the classes Lion and Dog. The Roar() function is used by all of them. However, their functions are different. We created a standard interface called sound test() that accepts any object and runs its Roar() function in order to take use of polymorphism. As a consequence, when we gave the pet and street objects to the sound test() function, it responded as predicted.

Lion can roar
Dog can't roar

Data Abstraction

Encapsulation and data abstraction are commonly used interchangeably. The two phrases are practically interchangeable since encapsulation is how data abstraction is accomplished. Internal details are concealed and just functionality is shown when abstraction is used. The act of abstracting anything involves giving it labels that encapsulate the essence of what a function or an entire program performs.