Object-Oriented Programming (OOP) is a programming paradigm based on objects rather than logic. Python fully supports OOP with its intuitive syntax. Let's explore key concepts:
🧱 Classes and Objects
- Class: A blueprint for creating objects. Example:
class Dog: def __init__(self, name): self.name = name
- Object: An instance of a class. Example:
my_dog = Dog("Buddy")
🔄 Inheritance
- Allows new classes to inherit properties from existing ones.
class Puppy(Dog): def play(self): print(f"{self.name} is playing!")
- Parent Class: Base class (e.g.,
Dog
) - Child Class: Derived class (e.g.,
Puppy
)
🪄 Polymorphism
- Method Overriding: Reimplementing parent methods in child classes
- Method Overloading: Not directly supported in Python, but achievable via default parameters
🔒 Encapsulation
- Bundling data and methods in a class while restricting direct access
class BankAccount: def __init__(self): self._balance = 0 # Protected attribute def deposit(self, amount): self._balance += amount
- Use underscores to indicate internal use
📚 Extend Your Knowledge
For visual learners, try this interactive Python OOP diagram to see class relationships. 🎨