4. Object-Oriented Programming (OOP)
4.1 What is OOP?
- Object-Oriented Programming is a programming paradigm that uses “objects” to design applications.
- Each object represents a real-world entity and contains:
- Attributes (data about the object)
- Methods (functions that define the object’s behavior)
- Attributes (data about the object)
4.2 Classes and Objects
- A class is a blueprint or template to create objects.
- An object is an instance of a class.
Example:
class Pet:
def __init__(self, name):self.name = name
def speak(self):
print("Hi, I'm", self.name)my_pet = Pet(“Bobby”)
my_pet.speak() # Output: Hi, I’m Bobby
__init__is called a constructor. It runs when an object is created and initializes attributes.selfrefers to the current object.
4.3 Encapsulation and Data Hiding
- Encapsulation: Combining data and methods within a single unit (a class).
- Data hiding: Use underscore
_to indicate private attributes that should not be modified directly.
Example:
class BankAccount:
def __init__(self, balance):self._balance = balance # underscore implies this is private
def deposit(self, amount):self._balance += amount
def withdraw(self, amount):
if self._balance >= amount:self._balance -= amount
else:
print("Insufficient funds") def get_balance(self):
return self._balance4.4 Inheritance
- Allows one class (child) to inherit properties from another (parent).
Example:
class Animal:
def speak(self):
print("Animal sound")class Dog(Animal):
def speak(self):
print("Woof!")Doginherits thespeakmethod fromAnimalbut overrides it.
4.5 Polymorphism
- Polymorphism means “many forms”. It allows a single function or method to work in different ways depending on the object.
- The overridden method in the subclass is used instead of the one in the parent class.
Example:
animals = [Dog(), Animal()]
for a in animals:a.speak() # Dog will say Woof!, Animal will say Animal sound