What is OOP and how to implement it in Python
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects, which are instances of classes. This approach enables modular, reusable, and scalable code by structuring programs based on real-world entities. OOP is built on four fundamental principles: Encapsulation, Abstraction, Inheritance, and Polymorphism.
Encapsulation restricts direct access to certain data within an object, ensuring controlled modifications through methods.
Abstraction hides complex implementation details while exposing only essential functionalities to the user.
Inheritance allows a class (child) to acquire attributes and behaviors from another class (parent), promoting code reuse.
Polymorphism enables a single interface to be used for different underlying data types, allowing methods to be overridden or dynamically adapted for various contexts. These principles collectively enhance code maintainability, efficiency, and scalability in software development.
1. Classes and Objects
class Dog:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute
def bark(self): # Method
print(f"{self.name} says Woof!")
dog1 = Dog("Buddy", 5)
dog2 = Dog("Bella", 3)
dog1.bark() # Output: Buddy says Woof!
dog2.bark() # Output: Bella says Woof!
2. Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self): # Public method
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
3. Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass # Abstract method
class Dog(Animal):
def speak(self):
print(f"{self.name} says Woof!")
class Cat(Animal):
def speak(self):
print(f"{self.name} says Meow!")
dog = Dog("Buddy")
cat = Cat("Whiskers")
dog.speak() # Output: Buddy says Woof!
cat.speak() # Output: Whiskers says Meow!
4. Polymorphism
class Bird(Animal):
def speak(self):
print(f"{self.name} says Chirp!")
animals = [Dog("Buddy"), Cat("Whiskers"), Bird("Tweety")]
for animal in animals:
animal.speak() # Output: Buddy says Woof!, Whiskers says Meow!, Tweety says Chirp!