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