Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects that contain both data and behavior. In this tutorial, you’ll learn:
Classes and Objects
Attributes and Methods
The Four Pillars of OOP: Encapsulation, Inheritance, Polymorphism, and Abstraction
Advanced OOP concepts in Python
11.2 Why Object-Oriented Programming?
OOP helps you: - Organize complex code into manageable pieces - Reuse code through inheritance - Model real-world entities naturally - Maintain large codebases more easily
11.3 Classes and Objects
11.4 What are Classes and Objects?
Class: A blueprint or template for creating objects
Object: An instance of a class (a specific example)
# Define a simple classclass Dog:pass# Empty class for now# Create objects (instances) of the classdog1 = Dog()dog2 = Dog()print(f"dog1 is a {type(dog1)}")print(f"dog2 is a {type(dog2)}")print(f"Are they the same object? {dog1 is dog2}")
dog1 is a <class '__main__.Dog'>
dog2 is a <class '__main__.Dog'>
Are they the same object? False
11.6 Adding Attributes
Attributes are variables that belong to an object.
class Dog:# Class attribute (shared by all instances) species ="Canis familiaris"# Instance attributes (unique to each instance)def__init__(self, name, age):self.name = nameself.age = age# Create dog instancesbuddy = Dog("Buddy", 3)charlie = Dog("Charlie", 5)print(f"{buddy.name} is {buddy.age} years old")print(f"{charlie.name} is {charlie.age} years old")print(f"Both are {buddy.species}")
Buddy is 3 years old
Charlie is 5 years old
Both are Canis familiaris
11.7 Understanding __init__ and self
__init__: Special method called when creating a new object (constructor)
self: Refers to the instance being created/used
class Person:def__init__(self, name, age):print(f"Creating a Person object for {name}")self.name = nameself.age = ageself.hobbies = []person1 = Person("Alice", 25)person1.hobbies.append("Reading")print(f"{person1.name}'s hobbies: {person1.hobbies}")
Creating a Person object for Alice
Alice's hobbies: ['Reading']
11.8 Adding Methods
Methods are functions that belong to a class.
class Dog:def__init__(self, name, age):self.name = nameself.age = agedef bark(self):returnf"{self.name} says Woof!"def get_human_years(self):returnself.age *7buddy = Dog("Buddy", 3)print(buddy.bark())print(f"{buddy.name} is {buddy.get_human_years()} in human years")
Alice's balance: $1000
Deposited $500. New balance: $1500
Withdrew $200. New balance: $1300
Alice's balance: $1300
11.10 The Four Pillars of OOP
11.11 Encapsulation
Encapsulation means bundling data and methods together, and controlling access to them.
Public, Protected, and Private Attributes
class Employee:def__init__(self, name, salary):self.name = name # Public attributeself._department ="IT"# Protected (convention: single underscore)self.__salary = salary # Private (name mangling: double underscore)def get_salary(self):returnself.__salarydef set_salary(self, amount):if amount >0:self.__salary = amountelse:print("Invalid salary amount")def display_info(self):returnf"{self.name} - Department: {self._department} - Salary: ${self.__salary}"emp = Employee("Bob", 50000)print(emp.name) # Accessibleprint(emp._department) # Accessible but not recommendedprint(emp.get_salary()) # Use method to access private attribute# This won't work as expected:# print(emp.__salary) # AttributeError# You can still access through name mangling (but shouldn't in practice)print(emp._Employee__salary) # Not recommended!
Abstraction hides complex implementation details and shows only necessary features.
from abc import ABC, abstractmethodclass PaymentProcessor(ABC):@abstractmethoddef process_payment(self, amount):"""All payment processors must implement this"""pass@abstractmethoddef refund(self, amount):"""All payment processors must implement this"""passclass CreditCardProcessor(PaymentProcessor):def process_payment(self, amount):returnf"Processing ${amount} via Credit Card"def refund(self, amount):returnf"Refunding ${amount} to Credit Card"class PayPalProcessor(PaymentProcessor):def process_payment(self, amount):returnf"Processing ${amount} via PayPal"def refund(self, amount):returnf"Refunding ${amount} to PayPal account"# Can't instantiate abstract class# processor = PaymentProcessor() # This would raise an error# But can instantiate concrete implementationscc_processor = CreditCardProcessor()pp_processor = PayPalProcessor()print(cc_processor.process_payment(100))print(pp_processor.process_payment(50))
Processing $100 via Credit Card
Processing $50 via PayPal
11.15 Advanced OOP Concepts
11.16 Class vs Instance Attributes
class Counter:# Class attribute (shared by all instances) total_count =0def__init__(self, name):self.name = name # Instance attributeself.count =0# Instance attribute Counter.total_count +=1# Increment class attributedef increment(self):self.count +=1# Create multiple countersc1 = Counter("Counter1")c2 = Counter("Counter2")c3 = Counter("Counter3")c1.increment()c1.increment()c2.increment()print(f"{c1.name}: {c1.count}")print(f"{c2.name}: {c2.count}")print(f"Total counters created: {Counter.total_count}")
Counter1: 2
Counter2: 1
Total counters created: 3
11.17 Class Methods and Static Methods
class Date:def__init__(self, year, month, day):self.year = yearself.month = monthself.day = daydef__str__(self):returnf"{self.year}-{self.month:02d}-{self.day:02d}"@classmethoddef from_string(cls, date_string):"""Alternative constructor""" year, month, day =map(int, date_string.split('-'))return cls(year, month, day)@classmethoddef today(cls):"""Factory method"""import datetime today = datetime.date.today()return cls(today.year, today.month, today.day)@staticmethoddef is_valid_date(year, month, day):"""Utility method that doesn't need instance or class"""return1<= month <=12and1<= day <=31# Regular constructordate1 = Date(2024, 1, 15)print(f"Regular constructor: {date1}")# Class method as alternative constructordate2 = Date.from_string("2024-06-20")print(f"From string: {date2}")# Static methodprint(f"Is 2024-02-30 valid? {Date.is_valid_date(2024, 2, 30)}")print(f"Is 2024-02-15 valid? {Date.is_valid_date(2024, 2, 15)}")
Regular constructor: 2024-01-15
From string: 2024-06-20
Is 2024-02-30 valid? True
Is 2024-02-15 valid? True
11.18 Property Decorators
Properties allow you to use methods like attributes.
class Temperature:def__init__(self, celsius):self._celsius = celsius@propertydef celsius(self):"""Get temperature in Celsius"""returnself._celsius@celsius.setterdef celsius(self, value):"""Set temperature in Celsius"""if value <-273.15:raiseValueError("Temperature cannot be below absolute zero")self._celsius = value@propertydef fahrenheit(self):"""Get temperature in Fahrenheit"""return (self._celsius *9/5) +32@fahrenheit.setterdef fahrenheit(self, value):"""Set temperature using Fahrenheit"""self.celsius = (value -32) *5/9# Use properties like attributestemp = Temperature(25)print(f"{temp.celsius}°C = {temp.fahrenheit}°F")temp.celsius =0print(f"{temp.celsius}°C = {temp.fahrenheit}°F")temp.fahrenheit =98.6print(f"{temp.celsius:.1f}°C = {temp.fahrenheit}°F")# Validation works through propertytry: temp.celsius =-300# Below absolute zeroexceptValueErroras e:print(f"Error: {e}")
25°C = 77.0°F
0°C = 32.0°F
37.0°C = 98.6°F
Error: Temperature cannot be below absolute zero
str: 'Python Crash Course' by Eric Matthes
repr: Book('Python Crash Course', 'Eric Matthes', 544)
Length: 544 pages
book1 == book2: False
book1 == book3: True
book2 < book1: True
Sorted by pages:
'Design Patterns' by Gang of Four - 395 pages
'Clean Code' by Robert Martin - 464 pages
'Python Crash Course' by Eric Matthes - 544 pages
More Magic Methods
class ShoppingCart:def__init__(self):self.items = []def add(self, item, price):self.items.append({'item': item, 'price': price})def__len__(self):"""Number of items"""returnlen(self.items)def__getitem__(self, index):"""Access items by index"""returnself.items[index]def__iter__(self):"""Make cart iterable"""returniter(self.items)def__contains__(self, item_name):"""Check if item exists using 'in'"""returnany(item['item'] == item_name for item inself.items)def__add__(self, other):"""Combine two carts""" new_cart = ShoppingCart() new_cart.items =self.items + other.itemsreturn new_cartcart1 = ShoppingCart()cart1.add("Laptop", 1200)cart1.add("Mouse", 25)cart2 = ShoppingCart()cart2.add("Keyboard", 75)# Use magic methodsprint(f"Cart has {len(cart1)} items") # __len__print(f"First item: {cart1[0]}") # __getitem__# Iteration with __iter__print("Items in cart:")for item in cart1:print(f" {item['item']}: ${item['price']}")# Check membership with __contains__print(f"Has Laptop? {'Laptop'in cart1}")# Combine carts with __add__combined = cart1 + cart2print(f"Combined cart has {len(combined)} items")
Cart has 2 items
First item: {'item': 'Laptop', 'price': 1200}
Items in cart:
Laptop: $1200
Mouse: $25
Has Laptop? True
Combined cart has 3 items
11.20 Composition vs Inheritance
Composition: “Has-a” relationship (more flexible)
class Engine:def__init__(self, horsepower):self.horsepower = horsepowerdef start(self):return"Engine started"def stop(self):return"Engine stopped"class Wheel:def__init__(self, size):self.size = size# Composition: Car HAS an Engine and HAS Wheelsclass Car:def__init__(self, brand, horsepower, wheel_size):self.brand = brandself.engine = Engine(horsepower) # Compositionself.wheels = [Wheel(wheel_size) for _ inrange(4)] # Compositiondef start(self):returnf"{self.brand}: {self.engine.start()}"def info(self):return (f"{self.brand} with {self.engine.horsepower}hp engine "f"and {self.wheels[0].size}\" wheels")car = Car("Toyota", 200, 17)print(car.start())print(car.info())
Toyota: Engine started
Toyota with 200hp engine and 17" wheels
11.21 Practical Examples
11.22 Library Management System
class Book:def__init__(self, isbn, title, author, year):self.isbn = isbnself.title = titleself.author = authorself.year = yearself.is_borrowed =Falsedef borrow(self):ifself.is_borrowed:returnf"'{self.title}' is already borrowed"self.is_borrowed =Truereturnf"You borrowed '{self.title}'"def return_book(self):ifnotself.is_borrowed:returnf"'{self.title}' was not borrowed"self.is_borrowed =Falsereturnf"You returned '{self.title}'"def__str__(self): status ="Borrowed"ifself.is_borrowed else"Available"returnf"{self.title} by {self.author} ({self.year}) - {status}"class Member:def__init__(self, member_id, name):self.member_id = member_idself.name = nameself.borrowed_books = []def borrow_book(self, book):iflen(self.borrowed_books) >=3:returnf"{self.name} has reached borrowing limit" message = book.borrow()if"borrowed"in message.lower() and"already"notin message.lower():self.borrowed_books.append(book)return messagedef return_book(self, book):if book inself.borrowed_books: message = book.return_book()self.borrowed_books.remove(book)return messagereturnf"{self.name} didn't borrow this book"def list_borrowed(self):ifnotself.borrowed_books:returnf"{self.name} has no borrowed books" books_list ="\n ".join(str(book) for book inself.borrowed_books)returnf"{self.name}'s borrowed books:\n{books_list}"class Library:def__init__(self, name):self.name = nameself.books = []self.members = []def add_book(self, book):self.books.append(book)def register_member(self, member):self.members.append(member)def find_book(self, title):for book inself.books:if title.lower() in book.title.lower():return bookreturnNonedef available_books(self):return [book for book inself.books ifnot book.is_borrowed]# Create librarylib = Library("City Library")# Add bookslib.add_book(Book("001", "Python Crash Course", "Eric Matthes", 2019))lib.add_book(Book("002", "Clean Code", "Robert Martin", 2008))lib.add_book(Book("003", "Design Patterns", "Gang of Four", 1994))# Register membermember = Member("M001", "Alice")lib.register_member(member)# Borrow booksbook1 = lib.find_book("Python")print(member.borrow_book(book1))book2 = lib.find_book("Clean Code")print(member.borrow_book(book2))# Show borrowed booksprint("\n"+ member.list_borrowed())# Show available booksprint(f"\nAvailable books in {lib.name}:")for book in lib.available_books():print(f" {book}")# Return a bookprint("\n"+ member.return_book(book1))print(member.list_borrowed())
You borrowed 'Python Crash Course'
You borrowed 'Clean Code'
Alice's borrowed books:
Python Crash Course by Eric Matthes (2019) - Borrowed
Clean Code by Robert Martin (2008) - Borrowed
Available books in City Library:
Design Patterns by Gang of Four (1994) - Available
You returned 'Python Crash Course'
Alice's borrowed books:
Clean Code by Robert Martin (2008) - Borrowed
11.23 E-commerce Product System
import jsonclass Product:def__init__(self, product_id, name, price, stock):self.product_id = product_idself.name = nameself.price = priceself.stock = stockdef update_stock(self, quantity):self.stock += quantitydef can_purchase(self, quantity):returnself.stock >= quantitydef purchase(self, quantity):ifself.can_purchase(quantity):self.stock -= quantityreturnTruereturnFalsedef__str__(self):returnf"{self.name} - ${self.price} (Stock: {self.stock})"class Electronics(Product):def__init__(self, product_id, name, price, stock, warranty_months):super().__init__(product_id, name, price, stock)self.warranty_months = warranty_monthsdef__str__(self): base =super().__str__()returnf"{base} - {self.warranty_months} months warranty"class Clothing(Product):def__init__(self, product_id, name, price, stock, size):super().__init__(product_id, name, price, stock)self.size = sizedef__str__(self): base =super().__str__()returnf"{base} - Size: {self.size}"class ShoppingCart:def__init__(self):self.items = [] # List of (product, quantity) tuplesdef add_item(self, product, quantity):if product.can_purchase(quantity):self.items.append((product, quantity))returnf"Added {quantity} x {product.name} to cart"returnf"Not enough stock for {product.name}"def remove_item(self, product):for item inself.items:if item[0] == product:self.items.remove(item)returnf"Removed {product.name} from cart"returnf"{product.name} not in cart"def get_total(self):returnsum(product.price * quantity for product, quantity inself.items)def checkout(self): total =0for product, quantity inself.items:if product.purchase(quantity): total += product.price * quantityelse:returnf"Failed: Not enough stock for {product.name}"self.items = []returnf"Purchase successful! Total: ${total:.2f}"def display(self):ifnotself.items:return"Cart is empty" result ="Shopping Cart:\n"for product, quantity inself.items: subtotal = product.price * quantity result +=f" {quantity} x {product.name} = ${subtotal:.2f}\n" result +=f"Total: ${self.get_total():.2f}"return result# Load products from JSONwithopen('data/products.json', 'r') as f: data = json.load(f)products = []for p in data['products']:if p['category'] =='Electronics': product = Electronics(p['id'], p['name'], p['price'], p['stock'], 12)else: product = Product(p['id'], p['name'], p['price'], p['stock']) products.append(product)print("Available Products:")for product in products:print(f" {product}")# Shopping simulationcart = ShoppingCart()print("\n"+ cart.add_item(products[0], 2)) # Laptopprint(cart.add_item(products[2], 5)) # Notebookprint("\n"+ cart.display())print("\n"+ cart.checkout())print("\nUpdated stock:")for product in products:print(f" {product}")
# Your code hereclass Student:passclass Course:pass# Test your codestudent1 = Student("Alice", "S001")student2 = Student("Bob", "S002")course = Course("Python Programming")course.enroll_student(student1)course.enroll_student(student2)
Solution:
Click to show solution
class Student:def__init__(self, name, student_id):self.name = nameself.student_id = student_idself.grades = []def add_grade(self, grade):if0<= grade <=100:self.grades.append(grade)returnf"Added grade {grade} for {self.name}"return"Invalid grade (must be 0-100)"def get_average(self):ifnotself.grades:return0returnsum(self.grades) /len(self.grades)def display_info(self): avg =self.get_average()returnf"{self.name} ({self.student_id}) - Average: {avg:.2f}"class Course:def__init__(self, course_name):self.course_name = course_nameself.students = []def enroll_student(self, student):self.students.append(student)returnf"{student.name} enrolled in {self.course_name}"def get_course_average(self):ifnotself.students:return0 total_avg =sum(s.get_average() for s inself.students)return total_avg /len(self.students)def display_roster(self): result =f"\n{self.course_name} Roster:\n"for student inself.students: result +=f" {student.display_info()}\n" result +=f"Course Average: {self.get_course_average():.2f}"return result# Teststudent1 = Student("Alice", "S001")student1.add_grade(85)student1.add_grade(92)student1.add_grade(88)student2 = Student("Bob", "S002")student2.add_grade(78)student2.add_grade(85)course = Course("Python Programming")print(course.enroll_student(student1))print(course.enroll_student(student2))print(course.display_roster())
Alice enrolled in Python Programming
Bob enrolled in Python Programming
Python Programming Roster:
Alice (S001) - Average: 88.33
Bob (S002) - Average: 81.50
Course Average: 84.92
11.27 Exercise 2: Vehicle Inheritance
Task: Create a vehicle hierarchy:
Base Vehicle class with: brand, model, year
Car class inheriting from Vehicle, add: num_doors
Motorcycle class inheriting from Vehicle, add: has_sidecar
2024 Toyota Camry - 4 doors
2023 Harley-Davidson Street 750 - no sidecar
11.28 Exercise 3: Employee System from File
Task: 1. Create an Employee class with: name, emp_id, position, salary 2. Read employee data from data/employees.txt 3. Create Employee objects from the file 4. Add methods: give_raise(), display_info() 5. Calculate total payroll
# Your code here
Solution:
Click to show solution
class Employee:def__init__(self, name, emp_id, position, salary):self.name = nameself.emp_id = emp_idself.position = positionself.salary = salarydef give_raise(self, percentage): increase =self.salary * (percentage /100)self.salary += increasereturnf"{self.name} received ${increase:.2f} raise"def display_info(self):returnf"{self.name} ({self.emp_id}) - {self.position}: ${self.salary:,.2f}"class Company:def__init__(self, name):self.name = nameself.employees = []def add_employee(self, employee):self.employees.append(employee)def load_from_file(self, filename):withopen(filename, 'r') asfile:for line infile: name, emp_id, position, salary = line.strip().split(',') employee = Employee(name, emp_id, position, float(salary))self.add_employee(employee)def total_payroll(self):returnsum(emp.salary for emp inself.employees)def display_all(self): result =f"\n{self.name} Employees:\n"for emp inself.employees: result +=f" {emp.display_info()}\n" result +=f"Total Payroll: ${self.total_payroll():,.2f}"return result# Load and displaycompany = Company("TechCorp")company.load_from_file('data/employees.txt')print(company.display_all())# Give raisesprint("\nGiving raises:")for emp in company.employees[:2]:print(" "+ emp.give_raise(10))print(company.display_all())
TechCorp Employees:
John (E001) - Developer: $75,000.00
Jane (E002) - Manager: $95,000.00
Bob (E003) - Designer: $65,000.00
Alice (E004) - Analyst: $70,000.00
Charlie (E005) - Developer: $72,000.00
Total Payroll: $377,000.00
Giving raises:
John received $7500.00 raise
Jane received $9500.00 raise
TechCorp Employees:
John (E001) - Developer: $82,500.00
Jane (E002) - Manager: $104,500.00
Bob (E003) - Designer: $65,000.00
Alice (E004) - Analyst: $70,000.00
Charlie (E005) - Developer: $72,000.00
Total Payroll: $394,000.00
11.29 Exercise 4: Advanced - Shape Calculator with Magic Methods
Task: Create shape classes that support: 1. Comparison operators (>, <, ==) based on area 2. Addition operator to combine shapes 3. String representation 4. Iteration over shapes
11.30 Exercise 5: Complete OOP Application - Todo List Manager
Task: Create a complete Todo List application with: 1. Task class with: title, description, priority, completed status 2. TodoList class with: add, remove, complete, filter by priority 3. Save/load from JSON file 4. Use properties, magic methods, and encapsulation
# Your code here
Solution:
Click to show solution
import jsonfrom datetime import datetimeclass Task:def__init__(self, title, description="", priority="medium"):self.title = titleself.description = descriptionself._priority = priorityself.completed =Falseself.created_at = datetime.now().strftime("%Y-%m-%d %H:%M")@propertydef priority(self):returnself._priority@priority.setterdef priority(self, value):if value in ['low', 'medium', 'high']:self._priority = valueelse:raiseValueError("Priority must be 'low', 'medium', or 'high'")def mark_complete(self):self.completed =Truedef mark_incomplete(self):self.completed =Falsedef to_dict(self):return {'title': self.title,'description': self.description,'priority': self._priority,'completed': self.completed,'created_at': self.created_at }@classmethoddef from_dict(cls, data): task = cls(data['title'], data['description'], data['priority']) task.completed = data['completed'] task.created_at = data['created_at']return taskdef__str__(self): status ="✓"ifself.completed else" "returnf"[{status}] {self.title} ({self._priority})"def__repr__(self):returnf"Task('{self.title}', priority='{self._priority}')"class TodoList:def__init__(self, name):self.name = nameself.tasks = []def add_task(self, task):self.tasks.append(task)returnf"Added: {task.title}"def remove_task(self, title):for task inself.tasks:if task.title == title:self.tasks.remove(task)returnf"Removed: {title}"returnf"Task '{title}' not found"def complete_task(self, title):for task inself.tasks:if task.title == title: task.mark_complete()returnf"Completed: {title}"returnf"Task '{title}' not found"def filter_by_priority(self, priority):return [task for task inself.tasks if task.priority == priority]def get_pending(self):return [task for task inself.tasks ifnot task.completed]def get_completed(self):return [task for task inself.tasks if task.completed]def save_to_file(self, filename): data = {'name': self.name,'tasks': [task.to_dict() for task inself.tasks] }withopen(filename, 'w') as f: json.dump(data, f, indent=2)returnf"Saved to {filename}"@classmethoddef load_from_file(cls, filename):withopen(filename, 'r') as f: data = json.load(f) todo_list = cls(data['name'])for task_data in data['tasks']: task = Task.from_dict(task_data) todo_list.add_task(task)return todo_listdef__len__(self):returnlen(self.tasks)def__iter__(self):returniter(self.tasks)def__str__(self): result =f"\n=== {self.name} ===\n"ifnotself.tasks: result +="No tasks yet!\n"else:for i, task inenumerate(self.tasks, 1): result +=f"{i}. {task}\n"return result# Test the applicationtodo = TodoList("My Tasks")# Add taskstodo.add_task(Task("Learn Python OOP", "Complete the tutorial", "high"))todo.add_task(Task("Write code", "Practice exercises", "medium"))todo.add_task(Task("Review concepts", "Go over notes", "low"))print(todo)# Complete a taskprint(todo.complete_task("Learn Python OOP"))# Filter by priorityprint("\nHigh priority tasks:")for task in todo.filter_by_priority("high"):print(f" {task}")# Show pendingprint(f"\nPending tasks ({len(todo.get_pending())} total):")for task in todo.get_pending():print(f" {task}")# Save to fileprint("\n"+ todo.save_to_file('exercises/todo_list.json'))# Load from fileprint("\nLoading from file...")loaded_todo = TodoList.load_from_file('exercises/todo_list.json')print(loaded_todo)