OOPs Concepts in Python
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure and organize code. Python supports OOP principles, which include encapsulation, inheritance, polymorphism, and abstraction. Below is an explanation of these concepts in Python:
1. **Encapsulation**
Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on the data into a single unit, called a class. It also restricts direct access to some of an object's components, which is achieved using access modifiers like private and protected.
**Example:**
```python
class Car:
def __init__(self, make, model):
self.make = make # Public attribute
self.__model = model # Private attribute
def display_info(self):
return f"Make: {self.make}, Model: {self.__model}"
# Creating an object
my_car = Car("Toyota", "Corolla")
print(my_car.display_info()) # Accessing public method
# print(my_car.__model) # This will raise an AttributeError (private attribute)
2. **Inheritance**
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). It promotes code reusability and hierarchical classification.
**Example:**
```python
class Vehicle: # Parent class
def __init__(self, make):
self.make = make
def display_make(self):
return f"Make: {self.make}"
class Car(Vehicle): # Child class
def __init__(self, make, model):
super().__init__(make) # Calling parent class constructor
self.model = model
def display_info(self):
return f"{self.display_make()}, Model: {self.model}"
# Creating an object
my_car = Car("Toyota", "Corolla")
print(my_car.display_info())
3. **Polymorphism**
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables methods to behave differently based on the object that calls them.
**Example:**
```python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Polymorphism in action
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak())
4. **Abstraction**
Abstraction involves hiding complex implementation details and exposing only the necessary features of an object. In Python, abstraction is achieved using abstract classes and interfaces.
**Example:**
```python
from abc import ABC, abstractmethod
class Shape(ABC): # Abstract class
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Creating an object
circle = Circle(5)
print("Area of circle:", circle.area())
```
Key Points:
- **Class**: A blueprint for creating objects.
- **Object**: An instance of a class.
- **Encapsulation**: Bundling data and methods, restricting access.
- **Inheritance**: Reusing code by creating subclasses.
- **Polymorphism**: Same method name but different implementations.
- **Abstraction**: Hiding complex details and exposing only essentials.
These concepts form the foundation of OOP in Python and help in writing modular, reusable, and maintainable code.
Comments
Post a Comment