OOP stands for Object Oriented Programming It is a programming method in which we use classes and objects to solve real-world problems. OOP helps us organize the code properly and makes it reusable
Python supports OOP concepts such as:
- Class
- Object
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
A class is a blueprint for creating objects Example:
class Student:
passHere Student is a class
An object is an instance of a class Example:
s1 = Student()Here s1 is an object of Student class
A constructor is a special function that runs automatically when an object is created In Python we use init() as constructor Example:
class Student:
def __init__(self,name):
self.name = name
s1 = Student("Naman")Encapsulation means wrapping data and methods into a single unit It is used to protect data from direct access Example:
class BankAccount:
def __init__(self):
self.__balance = 1000Here __balance is a private variable Advantages:
- Data security
- Better control on data
Inheritance allows one class to use properties and methods of another class Example:
class Employee:
def work(self):
print("Working")
class Manager(Employee):
passHere Manager inherits Employee.
Advantages:
- Code reuse
- Less coding
- Easy maintenance
Polymorphism means one method can have different forms Example:
class Car:
def start(self):
print("Car Starts")
class Bike:
def start(self):
print("Bike Starts")The same method start() gives different outputs Advantages:
- Flexibility
- Reusable code
Abstraction means hiding unnecessary details and showing only important information Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
passAdvantages:
- Hides complexity
- Makes code simple
Class-Blueprint,Logical entity ,Used to create objects Object-Instance,Physical entity, Created from class
- Code Reusability
- Easy Maintenance
- Better Security
- Easy to Understand
- Real World Representation