Python Object-Oriented Programming (OOP) Concepts Object-Oriented Programming (OOP) is a programming paradigm that organizes code using classes and objects to model real-world entities. Python, being an object-oriented language, provides robust support for OOP. Below are the key concepts:
- A class is a blueprint for creating objects. It defines properties (attributes) and behaviors (methods) that the objects created from it will have.
Pythonclass Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Car: {self.brand} {self.model}")- An object is an instance of a class. It represents a specific entity with its own data.
Pythonmy_car = Car("Toyota", "Corolla")
my_car.display_info() # Output: Car: Toyota Corolla- Inheritance allows a class (child) to inherit attributes and methods from another class (parent), promoting code reuse.
Pythonclass ElectricCar(Car):
def __init__(self, brand, model, battery_capacity):
super().__init__(brand, model)
self.battery_capacity = battery_capacity
def display_info(self):
print(f"Electric Car: {self.brand} {self.model}, Battery: {self.battery_capacity} kWh")
my_electric_car = ElectricCar("Tesla", "Model S", 100)
my_electric_car.display_info() # Output: Electric Car: Tesla Model S, Battery: 100 kWh- Polymorphism allows methods in different classes to have the same name but behave differently.
Pythonclass PetrolCar(Car):
def display_info(self):
print(f"Petrol Car: {self.brand} {self.model}")
car1 = ElectricCar("Tesla", "Model 3", 75)
car2 = PetrolCar("Honda", "Civic")
for car in (car1, car2):
car.display_info()- Encapsulation restricts access to certain attributes or methods, ensuring controlled interaction. Use underscores (_ or __) to indicate private or protected members.
Pythonclass BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500- Abstraction hides implementation details and shows only the essential features. This is often achieved using abstract base classes. Pythonfrom abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
circle = Circle(5)
print(circle.area()) # Output: 78.5Modularity: Code is organized into reusable classes.
Scalability: Easy to extend functionality.
Maintainability: Simplifies debugging and updates.
Reusability: Inheritance and polymorphism reduce redundancy.