OOP Core Concepts
OOP organizes code around "objects" rather than functions and logic.
Objects are instances of classes that contain data (attributes) and behavior (methods).
| Concept |
Python |
Real World |
| Class |
class Car: |
Car blueprint/design |
| Object |
my_car = Car() |
Actual Toyota Camry |
| self |
def drive(self): |
"This specific car" |
| Inheritance |
class ElectricCar(Car): |
Tesla inherits from Car |
Classes & Objects
class ClassName:
def __init__(self, parameters):
self.attribute = value
def method(self):
# Do something
First Class Example
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.miles = 0
def drive(self, miles):
self.miles += miles
return f"Drove {miles} miles"
def get_info(self):
return f"{self.year} {self.make} {self.model} ({self.miles} miles)"
# Create objects (instances)
toyota = Car("Toyota", "Camry", 2022)
tesla = Car("Tesla", "Model 3", 2023)
print(toyota.get_info()) # 2022 Toyota Camry (0 miles)
print(tesla.drive(10000)) # Drove 10000 miles
toyota Object
make: "Toyota"
model: "Camry"
year: 2022
miles: 0
tesla Object
make: "Tesla"
model: "Model 3"
year: 2023
miles: 0
Methods & Attributes
Instance Methods (self)
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
return f"Deposited ${amount}"
return "Invalid amount"
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
return f"Withdrew ${amount}"
return "Insufficient funds"
def get_balance(self):
return f"${self.balance:.2f}"
account = BankAccount("Alice", 1000)
print(account.deposit(500)) # Deposited $500
print(account.withdraw(200)) # Withdrew $200
print(account.get_balance()) # $1300.00
Class Methods & Static Methods
class MathUtils:
@classmethod
def circle_area(cls, radius):
return 3.14159 * radius ** 2
@staticmethod
def is_even(n):
return n % 2 == 0
print(MathUtils.circle_area(5)) # 78.54
print(MathUtils.is_even(4)) # True
Inheritance
class ElectricCar(Car):
⬇️
Inherits: drive(), get_info()
Adds: charge_battery(), get_range()
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def start_engine(self):
return f"{self.make} {self.model} engine started"
class ElectricCar(Car): # Inherits from Car
def __init__(self, make, model, battery_size):
super().__init__(make, model) # Call parent __init__
self.battery_size = battery_size
def charge_battery(self, hours):
return f"Charged for {hours} hours"
def get_range(self):
return f"{self.battery_size * 4} miles range"
tesla = ElectricCar("Tesla", "Model S", 100)
print(tesla.start_engine()) # Inherited ✓
print(tesla.charge_battery(2)) # New method
print(tesla.get_range()) # 400 miles range
Magic Methods (Dunder)
Custom Object Behavior
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __repr__(self):
return f"Vector2D({self.x}, {self.y})"
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
def __len__(self):
import math
return math.sqrt(self.x**2 + self.y**2)
v1 = Vector2D(3, 4)
v2 = Vector2D(1, 2)
print(v1) # Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
print(len(v1)) # 5.0 (magnitude)
Production OOP Examples
Employee Management System
class Employee:
raise_amount = 1.04 # Class variable
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f"{first}.{last}@company.com"
def fullname(self):
return f"{self.first} {self.last}"
def apply_raise(self):
self.pay *= self.raise_amount
class Developer(Employee):
raise_amount = 1.10 # 10% raise
def __init__(self, first, last, pay, language):
super().__init__(first, last, pay)
self.language = language
dev = Developer("John", "Doe", 50000, "Python")
print(dev.email) # john.doe@company.com
print(dev.fullname()) # John Doe
dev.apply_raise()
print(dev.pay) # 55000 (10% raise)
OOP Challenges
1. Library System
Book class → Library class (add/remove books, search, checkout)
2. Shape Hierarchy
Shape → Rectangle, Circle (area, perimeter methods)
3. Bank System
Account → SavingsAccount, CheckingAccount (deposit, withdraw, interest)
4. Game Characters
Character → Warrior, Mage (health, attack, special abilities)
OOP Professional!
🏆 Enterprise Applications:
🏦 Banking Systems
Accounts, Transactions, Customers
📱 Mobile Apps
UI Components, User Sessions
🎮 Games
Characters, Enemies, Weapons
🌐 Web Frameworks
Routes, Models, Controllers
💾 Databases
Tables, Queries, Relationships
You now build production-grade software architecture!
Next: Modules → Error Handling → Full Projects