## What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects containing both data and methods. Python fully supports OOP principles.
## Classes and Objects
“`
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f”Hi, I’m {self.name} and I’m {self.age} years old”
student1 = Student(“Alice”, 22)
print(student1.introduce())
“`
## Inheritance
“`
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f”{self.name} says Woof!”
class Cat(Animal):
def speak(self):
return f”{self.name} says Meow!”
animals = [Dog(“Buddy”), Cat(“Whiskers”)]
for animal in animals:
print(animal.speak())
“`
## Encapsulation
“`
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return f”Deposited ${amount}”
return “Invalid amount”
def get_balance(self):
return self.__balance
account = BankAccount(“John”, 1000)
print(account.deposit(500))
print(f”Balance: ${account.get_balance()}”)
“`
## Best Practices
– Use meaningful class and method names
– Follow the Single Responsibility Principle
– Prefer composition over inheritance when appropriate
– Use type hints for better code clarity
## Conclusion
OOP makes your code more modular, reusable, and maintainable. Practice these principles in every project.