Monday, April 3, 2023

OOP concepts in Python

Python is an Object Oriented Programming Language. In Python, everything is object, but everything is not in classes. The Basic OOP concepts are,

Abstraction

Python has to import Abstract Base Class to add the feature of abstraction.

from abc import ABC,abstractmethod

class Polygon(ABC):

   @abstractmethod    

   def sides(self):   

      pass  

  

class Triangle(Polygon):  # Polygon is parent

   def sides(self):   # all methods should pass self

      print("Triangle has 3 sides")   

class Square(Polygon):   

   def sides(self):   

      print("Square has 4 sides")       


Triangle().sides()   # Class() creates object

Square().sides()   # function call is outside any class


Polymorphism

Two ways of achieving this are,

1. Overloading

def add(p, q, r = 0):  # default value given to make parameter optional
    return p + q + r  
print (add(6, 23))  
print (add(22, 31, 544))  

2. Overriding

class Bird:  
    def intro(self):  
        print("There are multiple types of birds in the world.")  
    def flight(self):  
        print("Many of these birds can fly but some cannot.")  
  
class Sparrow(Birds):  
    def flight(self):  
        print("Sparrows are the birds which can fly.")  
      
class Ostrich(Birds):  
    def flight(self):  
        print("Ostriches are the birds which cannot fly.")  
      
Bird().intro()
Sparrow().intro()  # same as bird
Ostrich().flight()   # overridden method


Inheritance

A child class extends the parent and overrides its necessary methods. 

class Vehicle:
    def drive(self):
print("Parent")

class Car(Vehicle):   # single inheritance
    def __init__(self):  # constructor
       Vehicle.__init__(self)  # calling parent constructor
    def drive(self):
print("Child")

class Nano(Car,Bus):  # multiple inheritance
    def drive(self):
print("Grand Child")

print(issubclass(Car,Vehicle))  # returns True
n = Nano()  
print(isinstance(n,Nano))   # returns True

Every class inherits from the base class called Object.



Encapsulation

In Python, instance variables are declared inside the constructor. They can be of 3 types 

class Employee:
    def __init__(self, name, project, salary):
        self.name = name   # public- accessible everywhere
        self._project = project   # protected with single underscore- accessible within class and subclasses
        self.__salary = salary   # private with double underscore- accessible only within class

Private members can be accessed using public getter methods or by name mangling. Getters and Setters are declared only for private variables, others can be accessed with dot.

def get_salary(self):
    print('Salary:', self.__salary)
print('Salary:', new Employee()._Employee__salary) # one underscore before and two after
print('Project:', new Employee()._project)

No comments: