0% found this document useful (0 votes)
16 views24 pages

Tutorial Questions C211 Part B

This document outlines a Python OOP tutorial containing 10 sections with practical exercises related to Object-Oriented Programming concepts. Topics include classes and objects, class methods, encapsulation, inheritance, multiple inheritance, and polymorphism, each with specific learning objectives and programming tasks. The document serves as a comprehensive guide for students to reinforce their understanding of OOP principles through hands-on coding challenges.

Uploaded by

emmus000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views24 pages

Tutorial Questions C211 Part B

This document outlines a Python OOP tutorial containing 10 sections with practical exercises related to Object-Oriented Programming concepts. Topics include classes and objects, class methods, encapsulation, inheritance, multiple inheritance, and polymorphism, each with specific learning objectives and programming tasks. The document serves as a comprehensive guide for students to reinforce their understanding of OOP principles through hands-on coding challenges.

Uploaded by

emmus000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python OOP Tutorial Questions PART B

Based on CS111 Module - Copperbelt University

Instructor: George Mugala


February 16, 2026

Contents
1 Classes and Objects 3

2 Class Methods and Static Methods 5

3 Encapsulation and Properties 7

4 Inheritance 9

5 Multiple Inheritance and Mixins 11

6 Polymorphism 13

7 Special Methods (Magic Methods) 15

8 Abstract Base Classes (ABC) 17

9 Composition vs Inheritance 19

10 SOLID Principles 21

1
Introduction
This document contains 10 tutorial questions for each major Object-Oriented Program-
ming topic covered in the CS111 Python module. Each section includes practical pro-
gramming exercises designed to reinforce the concepts learned.

2
1 Classes and Objects
Learning Objectives
ˆ Understand class definition and object instantiation

ˆ Work with instance attributes and methods

ˆ Implement constructors ( init method)

ˆ Differentiate between class and instance attributes

1. Basic Class Creation: Create a class called Book with attributes title, author,
and year. Include a method get info() that returns a formatted string with the
book’s details. Create three book objects and display their information.
2. Instance Methods: Design a Rectangle class with attributes length and width.
Add methods to calculate area, perimeter, and determine if the rectangle is a square.
Create test objects to demonstrate all methods.
3. Class vs Instance Attributes: Create a Employee class where:
ˆ Class attribute: company name = ”CBU Technologies”
ˆ Instance attributes: name, position, salary
ˆ Method: display info() showing all details

Demonstrate how class attributes are shared across all instances.


4. Constructor with Default Values: Implement a Student class with a construc-
tor that has default values. Include attributes: name, age, major (default: ”Un-
declared”), and gpa (default: 0.0). Add a method to update GPA with validation
(0.0-4.0).
5. Object Interaction: Create two classes: Author and Book. An author should have
name and nationality. A book should have title, year, and an author object. Write
a method that displays the complete book information including author details.
6. Counter Implementation: Design a Counter class that:
ˆ Starts at 0 when created
ˆ Has methods: increment(), decrement(), reset()
ˆ Includes validation to prevent negative values
ˆ Has a get value() method to display current count

7. Bank Account Class: Create a BankAccount class with account number, holder
name, and balance. Implement methods for deposit, withdrawal (with sufficient
balance check), and display balance. Create two accounts and perform several
transactions.
8. Class Documentation: Create a Calculator class with methods for basic oper-
ations (add, subtract, multiply, divide). Include proper docstrings for the class and
each method. Demonstrate using the help() function to view the documentation.

3
9. Object Comparison: Implement a Time class with hours, minutes, and seconds.
Add a method is earlier than(other) that compares two time objects and re-
turns True if the current time is earlier than the other.

10. Class Variable Counting: Create a LibraryItem class that keeps track of how
many items have been created. Each item should have a unique ID (auto-incrementing),
title, and status (checked in/out). Implement methods to check out and return
items.

Challenge Question
Enhance the LibraryItem class to include overdue calculation. Items can be
checked out for 14 days. Add methods to calculate fines (K5 per day overdue)
and display item status with due dates.

4
2 Class Methods and Static Methods
Learning Objectives
ˆ Understand the purpose of @classmethod and @staticmethod decorators

ˆ Implement factory methods using class methods

ˆ Create utility functions with static methods

ˆ Differentiate between instance, class, and static methods

1. Basic Class Method: Create a Temperature class that stores temperature in


Celsius. Add a class method from fahrenheit() that creates a Temperature object
from Fahrenheit value. Include a static method is freezing() that returns True
if temperature is below 0°C.

2. Factory Methods: Design a Person class with name and birth year. Implement
class methods:

ˆ from birth year() - creates Person from birth year


ˆ from age() - creates Person from current age
ˆ from string() - parses ”Name,YYYY” format

3. Validation with Static Methods: Create a Email class with sender, recipient,
subject, and body. Add static methods to validate email addresses (must contain
@ and .) and subject line (not empty). Use these validations in the constructor.

4. Class Method for Object Counting: Enhance the UniversityCourse example


from the module. Track how many courses are created and implement a class
method get course count() that returns the total. Also add a class method to
create a course from a dictionary.

5. Static Method for Formatting: Create a Currency class that stores amount
and currency type (ZMW, USD, EUR). Implement static methods for:

ˆ format amount(amount, currency) - returns formatted string


ˆ convert zmw to usd(amount, rate) - performs conversion

6. Class Method Inheritance: Create a base class Vehicle with a class method
create default(). Then create Car and Motorcycle subclasses that override this
class method appropriately. Demonstrate how class methods work with inheritance.

7. Configuration Manager: Design a DatabaseConfig class that stores connection


parameters. Use class attributes for default configurations and class methods to
create different configuration presets (development, testing, production).

8. Math Utility Class: Create a MathUtils class with only static methods:

ˆ is prime(n) - checks if number is prime


ˆ gcd(a, b) - finds greatest common divisor

5
ˆ factorial(n) - calculates factorial
ˆ fibonacci(n) - returns nth Fibonacci number

Demonstrate using these methods without creating an instance.

9. Date Parser: Implement a Date class with day, month, year attributes. Add class
methods:

ˆ from string(date str, format) - parses different formats


ˆ today() - creates Date object for current date
ˆ from timestamp(ts) - creates from Unix timestamp

10. Logger Class: Create a Logger class with different logging levels (INFO, WARN-
ING, ERROR). Use class attributes for log levels. Implement:

ˆ Class method to set global log level


ˆ Static method to format log messages with timestamps
ˆ Instance methods for actual logging

6
3 Encapsulation and Properties
Learning Objectives
ˆ Understand data hiding and encapsulation principles

ˆ Implement getters and setters using @property decorator

ˆ Add validation logic when setting attributes

ˆ Create read-only and computed properties

1. Basic Property Implementation: Create a Person class with private attributes


name and age. Use properties to provide controlled access:

ˆ Name should be string and at least 2 characters


ˆ Age should be between 0 and 150
ˆ Make age read-only after initialization

2. Computed Properties: Design a Rectangle class with private attributes width


and height. Create properties for:

ˆ width and height with validation (¿0)


ˆ area (computed property, read-only)
ˆ perimeter (computed property, read-only)
ˆ is square (boolean property)

3. Property with Side Effects: Create a BankAccount class where setting the
balance through a property automatically logs the transaction to a history list.
Include a getter for transaction history that returns a copy (not the original list).

4. Temperature Conversion: Implement a Temperature class that stores temper-


ature internally in Kelvin. Create properties for:

ˆ celsius - converts from/to Kelvin


ˆ fahrenheit - converts from/to Kelvin
ˆ kelvin - direct access to raw value

Include validation (Kelvin cannot be negative).

5. Student Grade Management: Create a StudentGrades class with private at-


tributes for student name and a list of grades. Implement properties:

ˆ average - computes average grade


ˆ highest - finds highest grade
ˆ lowest - finds lowest grade
ˆ passed - boolean based on passing threshold

Grades should be between 0 and 100.

7
6. Password Security: Design a User class with username and password. Make
password a write-only property (can be set but not read directly). Include a method
check password(input) that verifies if the input matches the stored password.

7. Product Inventory: Create a Product class with private attributes for name,
price, and quantity. Implement properties with business rules:

ˆ Price must be > 0


ˆ Quantity cannot be negative
ˆ total value = price Ö quantity (computed)
ˆ in stock = quantity > 0 (boolean)

8. Delayed Property: Implement a DataLoader class that loads a large file only
when accessed. Use a property that loads the data on first access (lazy loading)
and caches it for subsequent accesses.

9. Validation Chain: Create an EmailMessage class with private attributes for


sender, recipient, subject, and body. Implement properties that validate:

ˆ Email addresses must be valid format


ˆ Subject cannot exceed 100 characters
ˆ Body cannot be empty

Chain validations so that invalid data raises appropriate exceptions.

10. Property Dependencies: Design a Circle class with private attribute radius.
Create properties for radius, diameter, circumference, and area. Ensure that chang-
ing radius updates all dependent properties correctly.

8
4 Inheritance
Learning Objectives
ˆ Understand inheritance hierarchies and ”is-a” relationships

ˆ Implement method overriding

ˆ Use super() to call parent class methods

ˆ Work with multiple levels of inheritance

1. Basic Inheritance: Create a base class Animal with attributes name and age, and
methods speak() (prints ”Animal speaks”) and describe(). Create subclasses Dog
and Cat that override the speak() method appropriately.

2. Vehicle Hierarchy: Design a vehicle inheritance hierarchy:

ˆ Base class: Vehicle (make, model, year, fuel efficiency)


ˆ Subclass: Car (add: num doors, trunk size)
ˆ Subclass: Truck (add: payload capacity, towing capacity)
ˆ Subclass: Motorcycle (add: engine size, has sidecar)

Implement a method calculate fuel cost(distance, price per liter) in the


base class.

3. Using super(): Create a class hierarchy for employees:

ˆ Person (name, age, address)


ˆ Employee inherits from Person (employee id, department, salary)
ˆ Manager inherits from Employee (bonus, team size)

Use super() in each constructor to initialize parent attributes. Override str ()


method at each level.

4. Method Overriding with Different Signatures: Create a Shape base class


with an area() method. Create subclasses Square (needs side), Rectangle (needs
length, width), and Circle (needs radius). Each subclass should have different
constructor parameters but all implement area correctly.

5. Protected Members: Create a base class Document with protected attributes


title and content. Add methods to read these attributes. Create Book and
Report subclasses that access these protected members directly and add their own
specific attributes.

6. Inheritance with Class Methods: Create a base class Database with a class
method connect() and instance methods for CRUD operations. Create subclasses
MySQLDatabase and PostgreSQLDatabase that override the class method while
maintaining the same interface.

7. Deep Inheritance: Create a 4-level inheritance hierarchy:

9
ˆ Level 1: ElectronicDevice (power on(), power off())
ˆ Level 2: Computer inherits from ElectronicDevice (boot(), shutdown())
ˆ Level 3: Laptop inherits from Computer (close lid(), battery status())
ˆ Level 4: GamingLaptop inherits from Laptop (gpu mode(), overclock())

Demonstrate how methods are inherited and overridden at each level.

8. Preventing Inheritance: Research and implement a class that cannot be inher-


ited from. Then create a normal class and attempt to inherit from it to demonstrate
the difference. (Hint: research init subclass or metaclasses)

9. Template Method Pattern: Create a base class DataProcessor with a template


method process() that defines steps: read data(), process data(), write data().
Make the process data() method abstract (raise NotImplementedError). Create
subclasses CSVProcessor and JSONProcessor that implement process data() dif-
ferently.

10. Inheritance vs Composition Decision: Create two solutions for a problem:

ˆ Use inheritance: Create ElectricCar inheriting from Car


ˆ Use composition: Create Car with Engine and Battery components

Compare and contrast both approaches. Which is better and why?

10
5 Multiple Inheritance and Mixins
Learning Objectives
ˆ Understand multiple inheritance concepts

ˆ Implement mixin classes for reusable functionality

ˆ Understand Method Resolution Order (MRO)

ˆ Identify appropriate use cases for multiple inheritance

1. Basic Multiple Inheritance: Create three classes: Flyer (with method fly()),
Swimmer (with method swim()), and Duck that inherits from both. Create a duck
object and demonstrate it can both fly and swim.

2. Mixin Classes: Create mixin classes for common functionalities:

ˆ TimestampMixin - adds created at and updated at attributes


ˆ JSONSerializableMixin - adds to json() and from json() methods
ˆ LoggableMixin - adds logging capabilities

Then create a User class that uses all three mixins.

3. Method Resolution Order (MRO): Create a diamond inheritance problem:

ˆ Class A with method greet() saying ”Hello from A”


ˆ Class B inherits from A, overrides greet() saying ”Hello from B”
ˆ Class C inherits from A, overrides greet() saying ”Hello from C”
ˆ Class D inherits from B and C

Examine the MRO using D. mro and predict which greet() method will be called.

4. Validation Mixins: Create validation mixins:

ˆ EmailValidatorMixin - validate email format


ˆ PhoneValidatorMixin - validate phone number format
ˆ AgeValidatorMixin - validate age range

Create a PersonForm class that uses these mixins for data validation.

5. Serialization Mixins: Implement mixins for different serialization formats:

ˆ XMLSerializableMixin
ˆ JSONSerializableMixin
ˆ YAMLSerializableMixin

Create a Configuration class that can use any of these mixins to save/load con-
figuration.

11
6. Conflict Resolution: Create two parent classes with the same method name but
different implementations. Demonstrate how to explicitly call a specific parent’s
method using the class name (e.g., [Link](self)).

7. Logger Mixin: Create a LoggerMixin that adds logging methods (info(), warn-
ing(), error()). Then create several unrelated classes (Database, API, FileProcessor)
that incorporate this mixin to gain logging capabilities without duplicating code.

8. Performance Tracking Mixin: Implement a PerformanceMixin that automat-


ically tracks execution time of methods. Use it to decorate specific methods in a
class and report their execution time.

9. Observer Pattern with Mixins: Create a ObservableMixin that adds methods


to attach/detach observers and notify them of changes. Then create a WeatherStation
class that uses this mixin and notifies observers when temperature changes.

10. Comprehensive Mixin System: Design a system for a role-playing game using
mixins:

ˆ MovableMixin - move(), stop()


ˆ AttackerMixin - attack(), defend()
ˆ MageMixin - cast spell(), regenerate mana()
ˆ HealerMixin - heal(), buff()

Create character classes (Warrior, Mage, Paladin, etc.) by combining appropriate


mixins.

12
6 Polymorphism
Learning Objectives
ˆ Understand polymorphism and duck typing

ˆ Implement polymorphic methods across different classes

ˆ Work with common interfaces

ˆ Design flexible, extensible code using polymorphism

1. Basic Polymorphism: Create three unrelated classes: Dog, Cat, and Bird, each
with a make sound() method. Write a function animal sounds(animals) that
takes a list of animals and calls make sound() on each, demonstrating polymor-
phism.

2. Payment Processing: Design a payment processing system:

ˆ Base interface: PaymentMethod with method process payment(amount)


ˆ Implementations: CreditCard, PayPal, BankTransfer, MobileMoney

Create a function that processes payments regardless of the payment method type.

3. Duck Typing: Create classes Car, Bicycle, and Boat. Each should have a
drive() method but with different implementations. Write a function go vehicle(vehicle)
that calls drive() on any object that has this method, demonstrating duck typing.

4. File Exporters: Implement polymorphic file exporters:

ˆ CSVExporter - exports data to CSV


ˆ JSONExporter - exports data to JSON
ˆ XMLExporter - exports data to XML
ˆ PDFExporter - exports data to PDF

Each should have the same interface: export(data, filename).

5. Polymorphic Shapes: Expand on the Shape example from the module. Add new
shapes: Parallelogram, Trapezoid, Ellipse. Create a function that calculates
total area of a mixed list of shapes.

6. Notification System: Design a notification system that can send messages through
different channels:

ˆ EmailNotifier - sends via email


ˆ SMSNotifier - sends via text message
ˆ PushNotifier - sends push notifications
ˆ SlackNotifier - sends to Slack channel

All should implement send(message, recipient). Create a function to broadcast


to multiple channels.

13
7. Polymorphic Iterator: Create different collection classes: ListCollection, DictionaryCollec
SetCollection. Each should implement get iterator() that returns an object
with has next() and next() methods. Demonstrate iterating through each collec-
tion polymorphically.

8. Strategy Pattern: Implement a sorting application that can use different sorting
strategies:

ˆ BubbleSort
ˆ QuickSort
ˆ MergeSort

Each strategy should have a sort(data) method. Allow the user to select which
strategy to use at runtime.

9. Polymorphic UI Components: Create UI component classes:

ˆ Button - click(), render()


ˆ TextBox - input(), render()
ˆ CheckBox - toggle(), render()
ˆ DropDown - select(), render()

Write a function render ui(components) that calls render() on all components,


regardless of their type.

10. Plugin Architecture: Design a plugin system where plugins are loaded dynami-
cally and all implement a common interface. Create a simple text processor that can
have different plugins (WordCounterPlugin, SpellCheckPlugin, GrammarCheckPlu-
gin). Demonstrate how new plugins can be added without modifying the core sys-
tem.

14
7 Special Methods (Magic Methods)
Learning Objectives
ˆ Understand Python’s special methods and their purposes

ˆ Implement operator overloading

ˆ Create string representations with str and repr

ˆ Make objects work with built-in functions and operators

1. String Representation: Create a Book class with title, author, and ISBN. Im-
plement both str (user-friendly) and repr (developer-friendly) methods.
Create a book object and demonstrate the difference between print() and direct
object inspection.

2. Arithmetic Operations: Create a Fraction class with numerator and denomi-


nator. Implement special methods for:

ˆ add - addition
ˆ sub - subtraction
ˆ mul - multiplication
ˆ truediv - division

Always simplify fractions to lowest terms.

3. Comparison Operators: Create a Student class with name and GPA. Implement
all comparison methods ( lt , le , eq , ne , gt , ge ) so students can
be compared based on GPA. Create a list of students and sort them.

4. Container Emulation: Create a ShoppingCart class that acts like a container.


Implement:

ˆ len - returns number of items


ˆ getitem - access items by index or name
ˆ setitem - add/modify items
ˆ delitem - remove items
ˆ contains - check if item exists

5. Callable Objects: Create a Counter class that implements call . Each time
the object is called, it should increment and return the current count. The counter
should be able to start from a specified value.

6. Context Manager: Implement a Timer context manager using enter and


exit methods. It should record the time taken to execute a block of code and
print it automatically when exiting the context.

7. Mathematical Operations: Create a ComplexNumber class (if Python didn’t have


one) with real and imaginary parts. Implement:

15
ˆ abs - magnitude
ˆ neg - negation
ˆ pos - positive
ˆ invert - conjugate

8. Attribute Access Control: Create a ProtectedAttributes class that uses


getattr and setattr to implement a system where certain attributes are
read-only after initialization. Also implement delattr to prevent deletion of
important attributes.

9. Indexing and Slicing: Create a Polynomial class that represents polynomials


(e.g., 3x² + 2x + 1). Implement:

ˆ getitem - get coefficient for a power


ˆ setitem - set coefficient for a power
ˆ iter - iterate over coefficients
ˆ reversed - iterate in reverse order

10. Complete Vector Class: Enhance the Vector example from the module. Add
more special methods:

ˆ matmul (@) for dot product


ˆ or (—) for cross product (in 3D)
ˆ pow for vector exponentiation (if meaningful)
ˆ format for custom formatting options

16
8 Abstract Base Classes (ABC)
Learning Objectives
ˆ Understand the purpose of abstract base classes

ˆ Implement abstract methods using @abstractmethod

ˆ Create formal interfaces in Python

ˆ Enforce implementation requirements in subclasses

1. Basic ABC: Create an abstract class Shape with abstract methods area() and
perimeter(). Create concrete subclasses Square and Circle that implement these
methods. Attempt to instantiate the abstract class and observe the error.

2. Data Storage Interface: Design an abstract class DataStorage with abstract


methods:

ˆ save(data, key)
ˆ load(key)
ˆ delete(key)
ˆ exists(key)

Create concrete implementations: FileStorage (saves to files) and DatabaseStorage


(saves to a database).

3. Multiple Abstract Methods: Create an abstract class Vehicle with abstract


methods start(), stop(), and accelerate(). Create concrete subclasses Car and
Motorcycle that implement all methods. What happens if a subclass forgets to
implement one?

4. Concrete Methods in ABC: Create an abstract class Animal with:

ˆ Abstract method: make sound()


ˆ Concrete method: describe() that returns ”I am a [species]”
ˆ Class attribute: species

Create subclasses Dog and Cat and demonstrate inheritance of the concrete method.

5. ABC with Properties: Create an abstract class Employee with:

ˆ Abstract property: salary (must be implemented)


ˆ Abstract method: calculate bonus()
ˆ Concrete method: display info()

Create subclasses HourlyEmployee and SalariedEmployee with appropriate im-


plementations.

17
6. Registering Virtual Subclasses: Create an abstract class Iterable (as an ex-
ercise, not using Python’s built-in). Then use register() to register built-in types
like list, tuple, dict as virtual subclasses. Demonstrate isinstance() checks.

7. Authentication Interface: Design an abstract class Authenticator with meth-


ods:

ˆ authenticate(username, password)
ˆ logout(user)
ˆ get current user()

Create concrete implementations: BasicAuth, OAuthAuthenticator, LDAPAuthenticator.

8. Template Method with ABC: Create an abstract class ReportGenerator with:

ˆ Abstract methods: extract data(), format report()


ˆ Concrete method: generate() that calls the abstract methods in sequence

Create subclasses PDFReportGenerator and HTMLReportGenerator.

9. ABC with Class Methods: Create an abstract class Deserializable with ab-
stract class methods:

ˆ from json(json str)


ˆ from xml(xml str)

Create a Person class that implements these class methods to create Person objects
from different formats.

10. Plugin System with ABC: Design a plugin system using ABCs:

ˆ Abstract class Plugin with abstract methods: initialize(), execute(),


cleanup()
ˆ Create multiple plugins: LoggingPlugin, ValidationPlugin, NotificationPlugin
ˆ Create a PluginManager that can load and execute all plugins polymorphically

18
9 Composition vs Inheritance
Learning Objectives
ˆ Understand the difference between ”is-a” and ”has-a” relationships

ˆ Identify when to use composition over inheritance

ˆ Implement composition in class design

ˆ Design flexible, loosely coupled systems

1. Basic Composition: Create a Computer class that uses composition:

ˆ CPU class with speed and cores


ˆ RAM class with size and type
ˆ Storage class with capacity and type (SSD/HDD)

The Computer class should have these components as attributes and delegate ap-
propriate methods to them.

2. Inheritance vs Composition Comparison: Solve the same problem both ways:

ˆ Problem: Model a university with students, courses, and enrollments


ˆ Solution A: Use inheritance (Student is Person, Course is Entity)
ˆ Solution B: Use composition (University has Students, has Courses)

Compare the two approaches and discuss pros and cons.

3. Dynamic Composition: Create a Character class for a game that can have
different abilities composed at runtime:

ˆ Ability classes: Flying, Swimming, Invisibility, Strength


ˆ Character can add/remove abilities dynamically
ˆ Methods like perform action() should use currently composed abilities

4. Strategy Pattern with Composition: Implement a PaymentProcessor class


that uses composition to change payment strategies:

ˆ PaymentStrategy interface (abstract class)


ˆ Concrete strategies: CreditCardStrategy, PayPalStrategy, CryptoStrategy
ˆ PaymentProcessor has a set strategy() method to change behavior at run-
time

5. Nested Composition: Model a house using composition:

ˆ House contains multiple Room objects


ˆ Room contains multiple Furniture objects
ˆ Furniture has properties like name, material, dimensions

19
Implement methods to calculate total house area and total furniture value.

6. Aggregation vs Composition: Create classes to demonstrate the difference:

ˆ Department and Professor (aggregation - professors exist independently)


ˆ House and Room (composition - rooms don’t exist without house)

Show how object lifetimes differ between these relationships.

7. Delegation Pattern: Create a Logger class and a FileManager class. Instead of


inheriting from Logger, use composition so FileManager delegates logging tasks to a
Logger instance. Show how this allows swapping different logger implementations.

8. Multiple Behaviors via Composition: Create a system where objects can have
multiple behaviors without multiple inheritance:

ˆ Behavior classes: WalkBehavior, FlyBehavior, SwimBehavior


ˆ Entity classes: Duck (walk, fly, swim), Fish (swim only), Parrot (walk, fly)
ˆ Use composition to give each entity the appropriate behaviors

9. Composition Over Inheritance Refactoring: Start with an inheritance-based


design:

ˆ Vehicle > Car > ElectricCar


ˆ Vehicle > Truck > ElectricTruck

Refactor it to use composition where Electric functionality is a component rather


than a base class. Discuss why this might be better.

10. Real-world System Design: Design a restaurant management system using com-
position. Include:

ˆ Restaurant (has menu, employees, tables)


ˆ Menu (has list of MenuItems)
ˆ Employee (has Role, Schedule)
ˆ Order (has Customer, list of MenuItems, PaymentMethod)

Explain why composition is more appropriate than inheritance for this system.

20
10 SOLID Principles
Learning Objectives
ˆ Understand the five SOLID principles of OOP design

ˆ Apply Single Responsibility Principle

ˆ Implement Open/Closed Principle

ˆ Ensure Liskov Substitution Principle

ˆ Design with Interface Segregation and Dependency Inversion

1. Single Responsibility Principle (SRP): Identify SRP violations in this class


and refactor it:
1 class User :
2 def __init__ ( self , name , email ) :
3 self . name = name
4 self . email = email
5

6 def save_to_database ( self ) :


7 # Database save code
8 pass
9

10 def send_email ( self ) :


11 # Email sending code
12 pass
13

14 def generate_report ( self ) :


15 # Report generation code
16 pass

2. Open/Closed Principle (OCP): Create a discount system that follows OCP:

ˆ Start with a DiscountCalculator that uses if/else for different customer types
ˆ Refactor to use polymorphism where new discount types can be added without
modifying existing code
ˆ Demonstrate adding a new ”VIP” discount without changing the calculator
core

3. Liskov Substitution Principle (LSP): Identify LSP violations in this hierarchy


and fix them:
1 class Bird :
2 def fly ( self ) :
3 return " Flying "
4

5 class Penguin ( Bird ) :


6 def fly ( self ) :
7 raise Exception ( " Penguins can ’t fly ! " )

21
8

9 class Ostrich ( Bird ) :


10 def fly ( self ) :
11 return " Ostriches can ’t fly either ! "

4. Interface Segregation Principle (ISP): Refactor this fat interface:

ˆ Worker interface with methods: work(), eat(), sleep(), manage(), attend meeting()
ˆ Classes: Developer, Manager, Robot, Intern

Split into smaller, more specific interfaces that classes can selectively implement.

5. Dependency Inversion Principle (DIP): Refactor this code to follow DIP:


1 class EmailSender :
2 def send ( self , message ) :
3 print ( f " Sending email : { message } " )
4

5 class N o t if i c at i o nS e r vi c e :
6 def __init__ ( self ) :
7 self . email_sender = EmailSender ()
8

9 def notify ( self , message ) :


10 self . email_sender . send ( message )

Make NotificationService depend on an abstraction rather than a concrete class.

6. All SOLID Principles Combined: Design a payroll system that adheres to all
SOLID principles:

ˆ Different employee types (hourly, salaried, commissioned)


ˆ Different payment methods (bank transfer, check, cash)
ˆ Tax calculations, benefits deductions
ˆ Report generation for accounting

7. SRP and OCP Exercise: Create a logging system where:

ˆ Different log destinations (file, database, console) each have their own class
(SRP)
ˆ New destinations can be added without modifying existing code (OCP)
ˆ Demonstrate by adding a ”cloud logging” destination

8. LSP and Inheritance: Create a geometric shape hierarchy that follows LSP:

ˆ Base class Shape with methods that make sense for all shapes
ˆ Subclasses: Rectangle, Square, Circle, Triangle
ˆ Ensure that any function working with Shape works correctly with all sub-
classes

9. ISP in UI Components: Design a UI component system following ISP:

22
ˆ Base interfaces: Clickable, Draggable, Resizable, Editable
ˆ Components: Button, TextBox, Window, Slider, Checkbox
ˆ Each component implements only the interfaces it needs

10. DIP with Dependency Injection: Implement a dependency injection container:

ˆ Create classes with dependencies (e.g., OrderService depends on PaymentProcessor


and InventoryService)
ˆ Implement a simple DI container that resolves dependencies automatically
ˆ Demonstrate how this follows DIP and makes testing easier

23
Additional Resources
Tips for Solving OOP Problems
ˆ Plan before coding: Sketch your class hierarchy and relationships

ˆ Start simple: Implement basic functionality first, then add complexity

ˆ Test incrementally: Test each class and method as you build them

ˆ Use docstrings: Document your classes and methods clearly

ˆ Follow naming conventions: CamelCase for classes, snake case for meth-
ods

ˆ Consider design patterns: Many problems have standard solutions

ˆ Refactor when needed: Don’t be afraid to restructure your code

Grading Rubric for Tutorial Questions


Each question will be evaluated on:

ˆ Correctness (40%) - Does the code work as expected?

ˆ Design (30%) - Is the OOP design appropriate and well-structured?

ˆ Code Quality (20%) - Is the code readable, documented, and following


conventions?

ˆ Completeness (10%) - Are edge cases handled and requirements fully met?

Submission Guidelines
1. Submit Python (.py) files for each question

2. Include comments and docstrings

3. Add test cases demonstrating your code works

4. Submit by the deadline specified by your instructor

24

You might also like