Programming Like the Real World
Object-Oriented Programming models software like real-world objects. Your bank account has a balance (data) and can deposit/withdraw (behavior). OOP captures this naturally.
Classes and Objects
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.speed = 0
def accelerate(self, amount):
self.speed += amount
print(f"{self.make} {self.model} is going {self.speed} km/h")
def brake(self):
self.speed = max(0, self.speed - 10)
def __str__(self):
return f"{self.year} {self.make} {self.model}"
# Create car objects
tesla = Car("Tesla", "Model 3", 2024)
bmw = Car("BMW", "M5", 2024)
tesla.accelerate(60)
print(tesla) # 2024 Tesla Model 3
Encapsulation: Protect Your Data
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private!
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
@property
def balance(self):
return self.__balance
account = BankAccount("Alice", 1000)
account.deposit(500)
print(account.balance) # 1500
Inheritance: Build on Existing Code
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
class Dog(Animal):
def bark(self):
print(f"{self.name}: Woof!")
class Cat(Animal):
def meow(self):
print(f"{self.name}: Meow!")
dog = Dog("Rex")
dog.eat() # Inherited from Animal
dog.bark() # Dog-specific
Polymorphism
class Shape:
def area(self):
raise NotImplementedError
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
shapes = [Circle(5), Square(4)]
for shape in shapes:
print(f"Area: {shape.area()}")
OOP isn't just a technique—it's a way of thinking that scales to large, complex codebases.
