In Python, object-oriented programming (OOP) is supported, and it utilizes several key concepts known as the “four pillars of OOP” or “OOP principles.” These principles, also known as OOPs concepts, are:
- Encapsulation: It refers to the bundling of data and methods/functions that operate on that data within a single unit called a class. Encapsulation provides data hiding and protects the internal implementation of an object. Access to the data is restricted to the methods defined in the class.Example:
- class Car:
- def init(self, brand, color):
- self.brand = brand
- self.color = color
- self.speed = 0
- my_car = Car(“Tesla”, “red”)
- my_car.accelerate(20)
- print(my_car.speed) # Output: 20
- Inheritance: It allows creating a new class (derived class) by inheriting the properties and methods of an existing class (base or parent class). The derived class can extend or modify the behavior of the base class. Inheritance facilitates code reuse and supports the concept of hierarchical classification.
- Example:
- class Animal:
- def init(self, name):
- self.name = name
- class Dog(Animal):
- def speak(self):
- print(“Dog barks”)
- my_dog = Dog(“Buddy”)
- my_dog.speak() # Output: Dog barks
- Polymorphism: It allows objects of different classes to be treated as objects of a common base class. Polymorphism allows methods/functions to be written to accept objects of a base class and automatically work with objects of any derived class.Example:
- class Shape:
- def area(self):
- pass
- class Rectangle(Shape):
- def init(self, length, width):
- self.length = length
- self.width = width
- class Circle(Shape):
- def init(self, radius):
- self.radius = radius
- def print_area(shape):
- print(“Area:”, shape.area())
- rectangle = Rectangle(5, 3)
- circle = Circle(4)
- print_area(rectangle) # Output: Area: 15
- print_area(circle) # Output: Area: 50.24
- Abstraction: It involves hiding unnecessary implementation details and exposing only the essential features to the users. Abstraction helps in managing complexity by providing a simplified interface to interact with objects.Example:
- from abc import ABC, abstractmethod
- class Vehicle(ABC):
- @abstractmethod
- def start(self):
- pass
- class Car(Vehicle):
- def start(self):
- print(“Car started”)
- class Bike(Vehicle):
- def start(self):
- print(“Bike started”)
- car = Car()
- car.start() # Output: Car started
- bike = Bike()
- bike.start() # Output: Bike started