Aller au contenu

OOP - Object-Oriented Programming

Ce contenu n’est pas encore disponible dans votre langue.

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. It focuses on modeling real-world entities and their interactions. The four core principles of OOP are:

Encapsulation

Bundling data (attributes) and methods (functions) that operate on the data into a single unit (class). Restricts direct access to some of an object’s components.

Inheritance

A mechanism where a new class inherits properties and behavior from an existing class, promoting code reuse.

Polymorphism

The ability of objects to take on many forms. Allows one interface to be used for a general class of actions.

Abstraction

Hiding complex implementation details and showing only the essential features of an object.


Definition: Encapsulation is the mechanism of wrapping data (variables) and code (methods) together as a single unit, and restricting direct access to some of an object’s components.

Why Use It?

  • Protects the integrity of data.
  • Prevents unintended interference and misuse.
  • Makes code easier to maintain and modify.
class BankAccount:
def __init__(self, account_holder, balance=0):
self.__account_holder = account_holder # Private attribute
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return f"Deposited {amount}. New balance: {self.__balance}"
return "Invalid deposit amount."
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return f"Withdrew {amount}. New balance: {self.__balance}"
return "Insufficient funds or invalid amount."
def get_balance(self):
return self.__balance
# Usage
account = BankAccount("Alice", 1000)
print(account.deposit(500)) # Deposited 500. New balance: 1500
print(account.withdraw(200)) # Withdrew 200. New balance: 1300
print(account.get_balance()) # 1300

Definition: Inheritance allows a class (child) to inherit properties and methods from another class (parent). It promotes code reuse and establishes a relationship between classes.

Why Use It?

  • Avoids redundant code.
  • Makes it easier to create and maintain applications.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} barks!"
class Cat(Animal):
def speak(self):
return f"{self.name} meows!"
# Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy barks!
print(cat.speak()) # Whiskers meows!

Definition: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables one interface to represent different underlying forms (data types).

Why Use It?

  • Simplifies code by allowing a single interface to represent different types.
  • Enhances flexibility and extensibility.
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
# Usage
shapes = [Circle(5), Square(4)]
for shape in shapes:
print(f"Area: {shape.area()}") # Area: 78.5, Area: 16

Definition: Abstraction is the concept of hiding complex implementation details and showing only the essential features of an object. It helps reduce complexity and improve efficiency.

Why Use It?

  • Focuses on what an object does, not how it does it.
  • Simplifies interaction with objects.
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
return "Car started."
def stop(self):
return "Car stopped."
class Bike(Vehicle):
def start(self):
return "Bike started."
def stop(self):
return "Bike stopped."
# Usage
car = Car()
bike = Bike()
print(car.start()) # Car started.
print(bike.stop()) # Bike stopped.

Favor Composition Over Inheritance

Use composition (objects containing other objects) instead of inheritance to build complex functionality. It’s more flexible and avoids deep hierarchies.

Keep Classes Small and Focused

Each class should have a single responsibility. This makes your code easier to test, maintain, and extend.

Use Interfaces for Polymorphism

Define interfaces for common behaviors. This allows different classes to be used interchangeably.

Document Your Classes

Clearly document the purpose, attributes, and methods of each class. This helps other developers understand and use your code.



Let’s design a simple e-commerce system using OOP principles:

class Product:
def __init__(self, name, price):
self.__name = name
self.__price = price
def get_name(self):
return self.__name
def get_price(self):
return self.__price
class ShoppingCart:
def __init__(self):
self.__items = []
def add_item(self, product, quantity=1):
self.__items.append((product, quantity))
def calculate_total(self):
return sum(product.get_price() * quantity for product, quantity in self.__items)
class User:
def __init__(self, name, email):
self.__name = name
self.__email = email
self.__cart = ShoppingCart()
def add_to_cart(self, product, quantity=1):
self.__cart.add_item(product, quantity)
def checkout(self):
total = self.__cart.calculate_total()
return f"Order placed. Total: ${total:.2f}"
# Usage
laptop = Product("Laptop", 999.99)
phone = Product("Phone", 699.99)
user = User("Alice", "alice@example.com")
user.add_to_cart(laptop)
user.add_to_cart(phone, 2)
print(user.checkout()) # Order placed. Total: $2399.97

UML

Unified Modeling Language (UML) is a standard language for specifying, visualizing, and documenting the artifacts of an object-oriented system.

Design Patterns

Learn about common design patterns like Singleton, Factory, Observer, and more to solve recurring design problems.

SOLID Principles

SOLID is an acronym for five design principles to make software designs more understandable, flexible, and maintainable.