11  Object-Oriented Programming

11.1 Introduction

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)

Analogy: - Class = Cookie Cutter (blueprint) - Object = Cookie (actual instance)

11.5 Creating Your First Class

# Define a simple class
class Dog:
    pass  # Empty class for now

# Create objects (instances) of the class
dog1 = 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 = name
        self.age = age

# Create dog instances
buddy = 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 = name
        self.age = age
        self.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 = name
        self.age = age

    def bark(self):
        return f"{self.name} says Woof!"

    def get_human_years(self):
        return self.age * 7

buddy = Dog("Buddy", 3)
print(buddy.bark())
print(f"{buddy.name} is {buddy.get_human_years()} in human years")
Buddy says Woof!
Buddy is 21 in human years

11.9 Methods with Parameters

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}. New balance: ${self.balance}"
        return "Invalid deposit amount"

    def withdraw(self, amount):
        if amount > self.balance:
            return "Insufficient funds"
        if amount > 0:
            self.balance -= amount
            return f"Withdrew ${amount}. New balance: ${self.balance}"
        return "Invalid withdrawal amount"

    def get_balance(self):
        return f"{self.owner}'s balance: ${self.balance}"

# Create account and perform transactions
account = BankAccount("Alice", 1000)
print(account.get_balance())
print(account.deposit(500))
print(account.withdraw(200))
print(account.get_balance())
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 attribute
        self._department = "IT"       # Protected (convention: single underscore)
        self.__salary = salary        # Private (name mangling: double underscore)

    def get_salary(self):
        return self.__salary

    def set_salary(self, amount):
        if amount > 0:
            self.__salary = amount
        else:
            print("Invalid salary amount")

    def display_info(self):
        return f"{self.name} - Department: {self._department} - Salary: ${self.__salary}"

emp = Employee("Bob", 50000)
print(emp.name)                    # Accessible
print(emp._department)             # Accessible but not recommended
print(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!
Bob
IT
50000
50000

Why Encapsulation Matters

class Rectangle:
    def __init__(self, width, height):
        self.__width = width
        self.__height = height

    def get_area(self):
        return self.__width * self.__height

    def set_dimensions(self, width, height):
        # Validation logic
        if width > 0 and height > 0:
            self.__width = width
            self.__height = height
        else:
            print("Dimensions must be positive")

    def get_dimensions(self):
        return self.__width, self.__height

rect = Rectangle(5, 10)
print(f"Area: {rect.get_area()}")
rect.set_dimensions(7, 3)
print(f"New dimensions: {rect.get_dimensions()}")
rect.set_dimensions(-5, 10)  # Validation prevents invalid data
Area: 50
New dimensions: (7, 3)
Dimensions must be positive

11.12 Inheritance

Inheritance allows a class to inherit attributes and methods from another class.

Basic Inheritance

# Parent class (Base class / Superclass)
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Some sound"

    def info(self):
        return f"I am {self.name}"

# Child class (Derived class / Subclass)
class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

# Create instances
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.info())      # Inherited from Animal
print(dog.speak())     # Overridden in Dog

print(cat.info())      # Inherited from Animal
print(cat.speak())     # Overridden in Cat
I am Buddy
Woof!
I am Whiskers
Meow!

Using super()

class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def info(self):
        return f"{self.brand} {self.model}"

class Car(Vehicle):
    def __init__(self, brand, model, num_doors):
        super().__init__(brand, model)  # Call parent constructor
        self.num_doors = num_doors

    def info(self):
        # Extend parent method
        base_info = super().info()
        return f"{base_info} - {self.num_doors} doors"

class ElectricCar(Car):
    def __init__(self, brand, model, num_doors, battery_capacity):
        super().__init__(brand, model, num_doors)
        self.battery_capacity = battery_capacity

    def info(self):
        base_info = super().info()
        return f"{base_info} - {self.battery_capacity}kWh battery"

# Create instances
car = Car("Toyota", "Camry", 4)
electric = ElectricCar("Tesla", "Model 3", 4, 75)

print(car.info())
print(electric.info())
Toyota Camry - 4 doors
Tesla Model 3 - 4 doors - 75kWh battery

Inheritance Hierarchy Example

class Employee:
    def __init__(self, name, employee_id):
        self.name = name
        self.employee_id = employee_id

    def display(self):
        return f"Employee: {self.name} (ID: {self.employee_id})"

class Developer(Employee):
    def __init__(self, name, employee_id, programming_language):
        super().__init__(name, employee_id)
        self.programming_language = programming_language

    def display(self):
        base = super().display()
        return f"{base} - Language: {self.programming_language}"

class Manager(Employee):
    def __init__(self, name, employee_id, team_size):
        super().__init__(name, employee_id)
        self.team_size = team_size

    def display(self):
        base = super().display()
        return f"{base} - Team Size: {self.team_size}"

# Create different employee types
dev = Developer("Alice", "E001", "Python")
mgr = Manager("Bob", "E002", 5)

print(dev.display())
print(mgr.display())
Employee: Alice (ID: E001) - Language: Python
Employee: Bob (ID: E002) - Team Size: 5

11.13 Polymorphism

Polymorphism means “many forms” - different classes can have methods with the same name but different implementations.

class Shape:
    def area(self):
        pass

    def perimeter(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

    def perimeter(self):
        return 2 * 3.14159 * self.radius

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

class Triangle(Shape):
    def __init__(self, base, height, side1, side2):
        self.base = base
        self.height = height
        self.side1 = side1
        self.side2 = side2

    def area(self):
        return 0.5 * self.base * self.height

    def perimeter(self):
        return self.base + self.side1 + self.side2

# Polymorphism in action
shapes = [
    Circle(5),
    Rectangle(4, 6),
    Triangle(3, 4, 5, 5)
]

for i, shape in enumerate(shapes, 1):
    print(f"Shape {i}: {type(shape).__name__}")
    print(f"  Area: {shape.area():.2f}")
    print(f"  Perimeter: {shape.perimeter():.2f}")
    print()
Shape 1: Circle
  Area: 78.54
  Perimeter: 31.42

Shape 2: Rectangle
  Area: 24.00
  Perimeter: 20.00

Shape 3: Triangle
  Area: 6.00
  Perimeter: 13.00

Duck Typing

“If it walks like a duck and quacks like a duck, it’s a duck.”

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

class Duck:
    def speak(self):
        return "Quack!"

class Cow:
    def make_sound(self):  # Different method name
        return "Moo!"

def animal_sound(animal):
    # Duck typing: we don't check the type, just call the method
    try:
        return animal.speak()
    except AttributeError:
        return "This animal doesn't speak!"

animals = [Dog(), Cat(), Duck(), Cow()]

for animal in animals:
    print(f"{type(animal).__name__}: {animal_sound(animal)}")
Dog: Woof!
Cat: Meow!
Duck: Quack!
Cow: This animal doesn't speak!

11.14 Abstraction

Abstraction hides complex implementation details and shows only necessary features.

from abc import ABC, abstractmethod

class PaymentProcessor(ABC):
    @abstractmethod
    def process_payment(self, amount):
        """All payment processors must implement this"""
        pass

    @abstractmethod
    def refund(self, amount):
        """All payment processors must implement this"""
        pass

class CreditCardProcessor(PaymentProcessor):
    def process_payment(self, amount):
        return f"Processing ${amount} via Credit Card"

    def refund(self, amount):
        return f"Refunding ${amount} to Credit Card"

class PayPalProcessor(PaymentProcessor):
    def process_payment(self, amount):
        return f"Processing ${amount} via PayPal"

    def refund(self, amount):
        return f"Refunding ${amount} to PayPal account"

# Can't instantiate abstract class
# processor = PaymentProcessor()  # This would raise an error

# But can instantiate concrete implementations
cc_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 = 0

    def __init__(self, name):
        self.name = name              # Instance attribute
        self.count = 0                # Instance attribute
        Counter.total_count += 1      # Increment class attribute

    def increment(self):
        self.count += 1

# Create multiple counters
c1 = 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 = year
        self.month = month
        self.day = day

    def __str__(self):
        return f"{self.year}-{self.month:02d}-{self.day:02d}"

    @classmethod
    def from_string(cls, date_string):
        """Alternative constructor"""
        year, month, day = map(int, date_string.split('-'))
        return cls(year, month, day)

    @classmethod
    def today(cls):
        """Factory method"""
        import datetime
        today = datetime.date.today()
        return cls(today.year, today.month, today.day)

    @staticmethod
    def is_valid_date(year, month, day):
        """Utility method that doesn't need instance or class"""
        return 1 <= month <= 12 and 1 <= day <= 31

# Regular constructor
date1 = Date(2024, 1, 15)
print(f"Regular constructor: {date1}")

# Class method as alternative constructor
date2 = Date.from_string("2024-06-20")
print(f"From string: {date2}")

# Static method
print(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

    @property
    def celsius(self):
        """Get temperature in Celsius"""
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        """Set temperature in Celsius"""
        if value < -273.15:
            raise ValueError("Temperature cannot be below absolute zero")
        self._celsius = value

    @property
    def fahrenheit(self):
        """Get temperature in Fahrenheit"""
        return (self._celsius * 9/5) + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        """Set temperature using Fahrenheit"""
        self.celsius = (value - 32) * 5/9

# Use properties like attributes
temp = Temperature(25)
print(f"{temp.celsius}°C = {temp.fahrenheit}°F")

temp.celsius = 0
print(f"{temp.celsius}°C = {temp.fahrenheit}°F")

temp.fahrenheit = 98.6
print(f"{temp.celsius:.1f}°C = {temp.fahrenheit}°F")

# Validation works through property
try:
    temp.celsius = -300  # Below absolute zero
except ValueError as 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

11.19 Magic Methods (Dunder Methods)

Magic methods customize object behavior.

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        """String representation for users"""
        return f"'{self.title}' by {self.author}"

    def __repr__(self):
        """String representation for developers"""
        return f"Book('{self.title}', '{self.author}', {self.pages})"

    def __len__(self):
        """Length of the book"""
        return self.pages

    def __eq__(self, other):
        """Equality comparison"""
        return self.title == other.title and self.author == other.author

    def __lt__(self, other):
        """Less than comparison (for sorting)"""
        return self.pages < other.pages

# Create books
book1 = Book("Python Crash Course", "Eric Matthes", 544)
book2 = Book("Clean Code", "Robert Martin", 464)
book3 = Book("Python Crash Course", "Eric Matthes", 544)

print(f"str: {str(book1)}")        # Uses __str__
print(f"repr: {repr(book1)}")      # Uses __repr__
print(f"Length: {len(book1)} pages")  # Uses __len__
print(f"book1 == book2: {book1 == book2}")  # Uses __eq__
print(f"book1 == book3: {book1 == book3}")  # Uses __eq__
print(f"book2 < book1: {book2 < book1}")    # Uses __lt__

# Sorting uses __lt__
books = [book1, book2, Book("Design Patterns", "Gang of Four", 395)]
books.sort()
print("\nSorted by pages:")
for book in books:
    print(f"  {book} - {len(book)} pages")
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"""
        return len(self.items)

    def __getitem__(self, index):
        """Access items by index"""
        return self.items[index]

    def __iter__(self):
        """Make cart iterable"""
        return iter(self.items)

    def __contains__(self, item_name):
        """Check if item exists using 'in'"""
        return any(item['item'] == item_name for item in self.items)

    def __add__(self, other):
        """Combine two carts"""
        new_cart = ShoppingCart()
        new_cart.items = self.items + other.items
        return new_cart

cart1 = ShoppingCart()
cart1.add("Laptop", 1200)
cart1.add("Mouse", 25)

cart2 = ShoppingCart()
cart2.add("Keyboard", 75)

# Use magic methods
print(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 + cart2
print(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 = horsepower

    def 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 Wheels
class Car:
    def __init__(self, brand, horsepower, wheel_size):
        self.brand = brand
        self.engine = Engine(horsepower)  # Composition
        self.wheels = [Wheel(wheel_size) for _ in range(4)]  # Composition

    def start(self):
        return f"{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 = isbn
        self.title = title
        self.author = author
        self.year = year
        self.is_borrowed = False

    def borrow(self):
        if self.is_borrowed:
            return f"'{self.title}' is already borrowed"
        self.is_borrowed = True
        return f"You borrowed '{self.title}'"

    def return_book(self):
        if not self.is_borrowed:
            return f"'{self.title}' was not borrowed"
        self.is_borrowed = False
        return f"You returned '{self.title}'"

    def __str__(self):
        status = "Borrowed" if self.is_borrowed else "Available"
        return f"{self.title} by {self.author} ({self.year}) - {status}"

class Member:
    def __init__(self, member_id, name):
        self.member_id = member_id
        self.name = name
        self.borrowed_books = []

    def borrow_book(self, book):
        if len(self.borrowed_books) >= 3:
            return f"{self.name} has reached borrowing limit"
        message = book.borrow()
        if "borrowed" in message.lower() and "already" not in message.lower():
            self.borrowed_books.append(book)
        return message

    def return_book(self, book):
        if book in self.borrowed_books:
            message = book.return_book()
            self.borrowed_books.remove(book)
            return message
        return f"{self.name} didn't borrow this book"

    def list_borrowed(self):
        if not self.borrowed_books:
            return f"{self.name} has no borrowed books"
        books_list = "\n  ".join(str(book) for book in self.borrowed_books)
        return f"{self.name}'s borrowed books:\n  {books_list}"

class Library:
    def __init__(self, name):
        self.name = name
        self.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 in self.books:
            if title.lower() in book.title.lower():
                return book
        return None

    def available_books(self):
        return [book for book in self.books if not book.is_borrowed]

# Create library
lib = Library("City Library")

# Add books
lib.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 member
member = Member("M001", "Alice")
lib.register_member(member)

# Borrow books
book1 = lib.find_book("Python")
print(member.borrow_book(book1))

book2 = lib.find_book("Clean Code")
print(member.borrow_book(book2))

# Show borrowed books
print("\n" + member.list_borrowed())

# Show available books
print(f"\nAvailable books in {lib.name}:")
for book in lib.available_books():
    print(f"  {book}")

# Return a book
print("\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 json

class Product:
    def __init__(self, product_id, name, price, stock):
        self.product_id = product_id
        self.name = name
        self.price = price
        self.stock = stock

    def update_stock(self, quantity):
        self.stock += quantity

    def can_purchase(self, quantity):
        return self.stock >= quantity

    def purchase(self, quantity):
        if self.can_purchase(quantity):
            self.stock -= quantity
            return True
        return False

    def __str__(self):
        return f"{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_months

    def __str__(self):
        base = super().__str__()
        return f"{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 = size

    def __str__(self):
        base = super().__str__()
        return f"{base} - Size: {self.size}"

class ShoppingCart:
    def __init__(self):
        self.items = []  # List of (product, quantity) tuples

    def add_item(self, product, quantity):
        if product.can_purchase(quantity):
            self.items.append((product, quantity))
            return f"Added {quantity} x {product.name} to cart"
        return f"Not enough stock for {product.name}"

    def remove_item(self, product):
        for item in self.items:
            if item[0] == product:
                self.items.remove(item)
                return f"Removed {product.name} from cart"
        return f"{product.name} not in cart"

    def get_total(self):
        return sum(product.price * quantity for product, quantity in self.items)

    def checkout(self):
        total = 0
        for product, quantity in self.items:
            if product.purchase(quantity):
                total += product.price * quantity
            else:
                return f"Failed: Not enough stock for {product.name}"
        self.items = []
        return f"Purchase successful! Total: ${total:.2f}"

    def display(self):
        if not self.items:
            return "Cart is empty"
        result = "Shopping Cart:\n"
        for product, quantity in self.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 JSON
with open('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 simulation
cart = ShoppingCart()
print("\n" + cart.add_item(products[0], 2))  # Laptop
print(cart.add_item(products[2], 5))    # Notebook

print("\n" + cart.display())

print("\n" + cart.checkout())

print("\nUpdated stock:")
for product in products:
    print(f"  {product}")
Available Products:
  Laptop - $999.99 (Stock: 50) - 12 months warranty
  Coffee Maker - $79.99 (Stock: 30)
  Notebook - $12.99 (Stock: 200)
  Headphones - $149.99 (Stock: 75) - 12 months warranty
  Desk Lamp - $39.99 (Stock: 100)

Added 2 x Laptop to cart
Added 5 x Notebook to cart

Shopping Cart:
  2 x Laptop = $1999.98
  5 x Notebook = $64.95
Total: $2064.93

Purchase successful! Total: $2064.93

Updated stock:
  Laptop - $999.99 (Stock: 48) - 12 months warranty
  Coffee Maker - $79.99 (Stock: 30)
  Notebook - $12.99 (Stock: 195)
  Headphones - $149.99 (Stock: 75) - 12 months warranty
  Desk Lamp - $39.99 (Stock: 100)

11.24 Bank Account System with Inheritance

class BankAccount:
    account_counter = 1000

    def __init__(self, owner, initial_balance=0):
        self.account_number = BankAccount.account_counter
        BankAccount.account_counter += 1
        self.owner = owner
        self._balance = initial_balance
        self.transactions = []

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            self.transactions.append(f"Deposit: +${amount}")
            return f"Deposited ${amount}. Balance: ${self._balance}"
        return "Invalid amount"

    def withdraw(self, amount):
        if amount > self._balance:
            return "Insufficient funds"
        if amount > 0:
            self._balance -= amount
            self.transactions.append(f"Withdrawal: -${amount}")
            return f"Withdrew ${amount}. Balance: ${self._balance}"
        return "Invalid amount"

    def get_balance(self):
        return self._balance

    def statement(self):
        result = f"\n--- Account Statement ---"
        result += f"\nAccount: {self.account_number}"
        result += f"\nOwner: {self.owner}"
        result += f"\nBalance: ${self._balance}\n"
        result += f"\nRecent Transactions:"
        for trans in self.transactions[-5:]:  # Last 5 transactions
            result += f"\n  {trans}"
        return result

class SavingsAccount(BankAccount):
    def __init__(self, owner, initial_balance=0, interest_rate=0.02):
        super().__init__(owner, initial_balance)
        self.interest_rate = interest_rate

    def add_interest(self):
        interest = self._balance * self.interest_rate
        self._balance += interest
        self.transactions.append(f"Interest: +${interest:.2f}")
        return f"Added ${interest:.2f} interest. Balance: ${self._balance:.2f}"

class CheckingAccount(BankAccount):
    def __init__(self, owner, initial_balance=0, overdraft_limit=500):
        super().__init__(owner, initial_balance)
        self.overdraft_limit = overdraft_limit

    def withdraw(self, amount):
        # Can withdraw up to overdraft limit
        if amount > self._balance + self.overdraft_limit:
            return "Exceeds overdraft limit"
        if amount > 0:
            self._balance -= amount
            self.transactions.append(f"Withdrawal: -${amount}")
            return f"Withdrew ${amount}. Balance: ${self._balance}"
        return "Invalid amount"

# Create different account types
savings = SavingsAccount("Alice", 1000, 0.05)
checking = CheckingAccount("Bob", 500, 200)

print(savings.deposit(500))
print(savings.add_interest())
print(savings.statement())

print("\n" + checking.withdraw(600))  # Uses overdraft
print(checking.withdraw(200))  # Would exceed limit
print(checking.statement())
Deposited $500. Balance: $1500
Added $75.00 interest. Balance: $1575.00

--- Account Statement ---
Account: 1000
Owner: Alice
Balance: $1575.0

Recent Transactions:
  Deposit: +$500
  Interest: +$75.00

Withdrew $600. Balance: $-100
Exceeds overdraft limit

--- Account Statement ---
Account: 1001
Owner: Bob
Balance: $-100

Recent Transactions:
  Withdrawal: -$600

11.25 Exercises

11.26 Exercise 1: Student Management System

Task: Create a student management system with the following requirements:

  1. Create a Student class with:
    • Attributes: name, student_id, grades (list)
    • Methods: add_grade(), get_average(), display_info()
  2. Create a Course class with:
    • Attributes: course_name, students (list)
    • Methods: enroll_student(), get_course_average()
# Your code here
class Student:
    pass

class Course:
    pass

# Test your code
student1 = 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 = name
        self.student_id = student_id
        self.grades = []

    def add_grade(self, grade):
        if 0 <= grade <= 100:
            self.grades.append(grade)
            return f"Added grade {grade} for {self.name}"
        return "Invalid grade (must be 0-100)"

    def get_average(self):
        if not self.grades:
            return 0
        return sum(self.grades) / len(self.grades)

    def display_info(self):
        avg = self.get_average()
        return f"{self.name} ({self.student_id}) - Average: {avg:.2f}"

class Course:
    def __init__(self, course_name):
        self.course_name = course_name
        self.students = []

    def enroll_student(self, student):
        self.students.append(student)
        return f"{student.name} enrolled in {self.course_name}"

    def get_course_average(self):
        if not self.students:
            return 0
        total_avg = sum(s.get_average() for s in self.students)
        return total_avg / len(self.students)

    def display_roster(self):
        result = f"\n{self.course_name} Roster:\n"
        for student in self.students:
            result += f"  {student.display_info()}\n"
        result += f"Course Average: {self.get_course_average():.2f}"
        return result

# Test
student1 = 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:

  1. Base Vehicle class with: brand, model, year
  2. Car class inheriting from Vehicle, add: num_doors
  3. Motorcycle class inheriting from Vehicle, add: has_sidecar
  4. All should have a display_info() method
# Your code here

Solution:

Click to show solution
class Vehicle:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

    def display_info(self):
        return f"{self.year} {self.brand} {self.model}"

class Car(Vehicle):
    def __init__(self, brand, model, year, num_doors):
        super().__init__(brand, model, year)
        self.num_doors = num_doors

    def display_info(self):
        base = super().display_info()
        return f"{base} - {self.num_doors} doors"

class Motorcycle(Vehicle):
    def __init__(self, brand, model, year, has_sidecar=False):
        super().__init__(brand, model, year)
        self.has_sidecar = has_sidecar

    def display_info(self):
        base = super().display_info()
        sidecar = "with sidecar" if self.has_sidecar else "no sidecar"
        return f"{base} - {sidecar}"

# Test
car = Car("Toyota", "Camry", 2024, 4)
motorcycle = Motorcycle("Harley-Davidson", "Street 750", 2023, False)

print(car.display_info())
print(motorcycle.display_info())
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 = name
        self.emp_id = emp_id
        self.position = position
        self.salary = salary

    def give_raise(self, percentage):
        increase = self.salary * (percentage / 100)
        self.salary += increase
        return f"{self.name} received ${increase:.2f} raise"

    def display_info(self):
        return f"{self.name} ({self.emp_id}) - {self.position}: ${self.salary:,.2f}"

class Company:
    def __init__(self, name):
        self.name = name
        self.employees = []

    def add_employee(self, employee):
        self.employees.append(employee)

    def load_from_file(self, filename):
        with open(filename, 'r') as file:
            for line in file:
                name, emp_id, position, salary = line.strip().split(',')
                employee = Employee(name, emp_id, position, float(salary))
                self.add_employee(employee)

    def total_payroll(self):
        return sum(emp.salary for emp in self.employees)

    def display_all(self):
        result = f"\n{self.name} Employees:\n"
        for emp in self.employees:
            result += f"  {emp.display_info()}\n"
        result += f"Total Payroll: ${self.total_payroll():,.2f}"
        return result

# Load and display
company = Company("TechCorp")
company.load_from_file('data/employees.txt')
print(company.display_all())

# Give raises
print("\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

# Your code here

Solution:

Click to show solution
class Shape:
    def area(self):
        raise NotImplementedError("Subclass must implement area()")

    def __eq__(self, other):
        return self.area() == other.area()

    def __lt__(self, other):
        return self.area() < other.area()

    def __gt__(self, other):
        return self.area() > other.area()

    def __add__(self, other):
        """Combine areas"""
        return self.area() + other.area()

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def __str__(self):
        return f"Rectangle({self.width}x{self.height})"

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

    def __str__(self):
        return f"Circle(r={self.radius})"

class ShapeCollection:
    def __init__(self):
        self.shapes = []

    def add(self, shape):
        self.shapes.append(shape)

    def __iter__(self):
        return iter(self.shapes)

    def __len__(self):
        return len(self.shapes)

    def total_area(self):
        return sum(shape.area() for shape in self.shapes)

# Test
rect1 = Rectangle(5, 10)
rect2 = Rectangle(3, 8)
circle = Circle(5)

print(f"{rect1}: Area = {rect1.area()}")
print(f"{circle}: Area = {circle.area():.2f}")

print(f"\n{rect1} > {rect2}? {rect1 > rect2}")
print(f"{rect1} == {circle}? {rect1 == circle}")

combined_area = rect1 + circle
print(f"\nCombined area: {combined_area:.2f}")

# Collection
collection = ShapeCollection()
collection.add(rect1)
collection.add(rect2)
collection.add(circle)

print(f"\nShape Collection ({len(collection)} shapes):")
for shape in collection:
    print(f"  {shape}: {shape.area():.2f}")
print(f"Total area: {collection.total_area():.2f}")
Rectangle(5x10): Area = 50
Circle(r=5): Area = 78.54

Rectangle(5x10) > Rectangle(3x8)? True
Rectangle(5x10) == Circle(r=5)? False

Combined area: 128.54

Shape Collection (3 shapes):
  Rectangle(5x10): 50.00
  Rectangle(3x8): 24.00
  Circle(r=5): 78.54
Total area: 152.54

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 json
from datetime import datetime

class Task:
    def __init__(self, title, description="", priority="medium"):
        self.title = title
        self.description = description
        self._priority = priority
        self.completed = False
        self.created_at = datetime.now().strftime("%Y-%m-%d %H:%M")

    @property
    def priority(self):
        return self._priority

    @priority.setter
    def priority(self, value):
        if value in ['low', 'medium', 'high']:
            self._priority = value
        else:
            raise ValueError("Priority must be 'low', 'medium', or 'high'")

    def mark_complete(self):
        self.completed = True

    def mark_incomplete(self):
        self.completed = False

    def to_dict(self):
        return {
            'title': self.title,
            'description': self.description,
            'priority': self._priority,
            'completed': self.completed,
            'created_at': self.created_at
        }

    @classmethod
    def from_dict(cls, data):
        task = cls(data['title'], data['description'], data['priority'])
        task.completed = data['completed']
        task.created_at = data['created_at']
        return task

    def __str__(self):
        status = "✓" if self.completed else " "
        return f"[{status}] {self.title} ({self._priority})"

    def __repr__(self):
        return f"Task('{self.title}', priority='{self._priority}')"

class TodoList:
    def __init__(self, name):
        self.name = name
        self.tasks = []

    def add_task(self, task):
        self.tasks.append(task)
        return f"Added: {task.title}"

    def remove_task(self, title):
        for task in self.tasks:
            if task.title == title:
                self.tasks.remove(task)
                return f"Removed: {title}"
        return f"Task '{title}' not found"

    def complete_task(self, title):
        for task in self.tasks:
            if task.title == title:
                task.mark_complete()
                return f"Completed: {title}"
        return f"Task '{title}' not found"

    def filter_by_priority(self, priority):
        return [task for task in self.tasks if task.priority == priority]

    def get_pending(self):
        return [task for task in self.tasks if not task.completed]

    def get_completed(self):
        return [task for task in self.tasks if task.completed]

    def save_to_file(self, filename):
        data = {
            'name': self.name,
            'tasks': [task.to_dict() for task in self.tasks]
        }
        with open(filename, 'w') as f:
            json.dump(data, f, indent=2)
        return f"Saved to {filename}"

    @classmethod
    def load_from_file(cls, filename):
        with open(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_list

    def __len__(self):
        return len(self.tasks)

    def __iter__(self):
        return iter(self.tasks)

    def __str__(self):
        result = f"\n=== {self.name} ===\n"
        if not self.tasks:
            result += "No tasks yet!\n"
        else:
            for i, task in enumerate(self.tasks, 1):
                result += f"{i}. {task}\n"
        return result

# Test the application
todo = TodoList("My Tasks")

# Add tasks
todo.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 task
print(todo.complete_task("Learn Python OOP"))

# Filter by priority
print("\nHigh priority tasks:")
for task in todo.filter_by_priority("high"):
    print(f"  {task}")

# Show pending
print(f"\nPending tasks ({len(todo.get_pending())} total):")
for task in todo.get_pending():
    print(f"  {task}")

# Save to file
print("\n" + todo.save_to_file('exercises/todo_list.json'))

# Load from file
print("\nLoading from file...")
loaded_todo = TodoList.load_from_file('exercises/todo_list.json')
print(loaded_todo)

=== My Tasks ===
1. [ ] Learn Python OOP (high)
2. [ ] Write code (medium)
3. [ ] Review concepts (low)

Completed: Learn Python OOP

High priority tasks:
  [✓] Learn Python OOP (high)

Pending tasks (2 total):
  [ ] Write code (medium)
  [ ] Review concepts (low)

Saved to exercises/todo_list.json

Loading from file...

=== My Tasks ===
1. [✓] Learn Python OOP (high)
2. [ ] Write code (medium)
3. [ ] Review concepts (low)

11.31 Summary

Congratulations! You’ve learned the fundamentals of Object-Oriented Programming in Python.

11.32 Key Concepts Recap

Basic OOP

  • Class: Blueprint for creating objects
  • Object: Instance of a class
  • __init__: Constructor method
  • self: Reference to the instance
  • Attributes: Variables belonging to objects
  • Methods: Functions belonging to classes

Four Pillars of OOP

  1. Encapsulation: Bundle data and methods, control access
    • Public, protected (_), private (__) attributes
    • Getter/setter methods
  2. Inheritance: Create new classes from existing ones
    • super() to call parent methods
    • Method overriding
  3. Polymorphism: Same interface, different implementations
    • Duck typing
    • Method overriding
  4. Abstraction: Hide complexity, show only essentials
    • Abstract base classes (ABC)
    • Abstract methods

Advanced Features

  • Class vs Instance Attributes
  • @classmethod and @staticmethod
  • @property decorators
  • Magic methods (str, repr, len, etc.)
  • Composition vs Inheritance

11.33 Quick Reference

# Basic class
class MyClass:
    class_attr = "shared"

    def __init__(self, value):
        self.instance_attr = value

    def method(self):
        return self.instance_attr

# Inheritance
class Child(Parent):
    def __init__(self, value):
        super().__init__(value)

# Properties
class MyClass:
    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, val):
        self._value = val

# Magic methods
class MyClass:
    def __str__(self):
        return "string representation"

    def __len__(self):
        return 10

11.34 Best Practices

  1. Use meaningful class and method names
  2. Keep classes focused (Single Responsibility Principle)
  3. Prefer composition over inheritance when appropriate
  4. Use encapsulation to protect data
  5. Implement magic methods for better usability
  6. Document your classes with docstrings

11.35 Next Steps

  • Learn about design patterns
  • Explore dataclasses (Python 3.7+)
  • Study SOLID principles
  • Practice with real-world projects

Happy coding!