Oop Using Python Module 2
Oop Using Python Module 2
Training Module
Contents
Course Overview 2
4 Updated Assessment 17
4.1 Continuous Assessment (40%) . . . . . . . . . . . . . . . . . . . . . . . . 17
4.2 Final Examination (60%) . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1
Python Programming Fundamentals George Mugala - Copperbelt University
Course Overview
This module introduces students to the fundamentals of Python programming language
with comprehensive coverage of Object-Oriented Programming (OOP). Python is a ver-
satile, high-level programming language known for its simplicity and readability. This
course covers basic syntax, data structures, control flow, functions, file handling, and
comprehensive OOP concepts.
Prerequisites
Basic computer literacy
2
Python Programming Fundamentals George Mugala - Copperbelt University
1 class Student :
2 " " " A class representing a CBU student " " "
3
4 # Class attribute ( shared by all instances )
5 university = " Copperbelt University "
6
7 # Constructor ( initializer )
8 def __init__ ( self , name , student_id , course ) :
9 " " " Initialize student attributes " " "
10 self . name = name # Instance attribute
11 self . student_id = student_id
12 self . course = course
13 self . grades = [] # Empty list for grades
14
15 # Instance method
16 def display_info ( self ) :
17 " " " Display student information " " "
18 print ( f " Student Name : { self . name } " )
19 print ( f " Student ID : { self . student_id } " )
20 print ( f " Course : { self . course } " )
21 print ( f " University : { self . university } " )
22 print ( f " Grades : { self . grades } " )
23
24 def add_grade ( self , grade ) :
25 " " " Add a grade to student ’s record " " "
26 if 0 <= grade <= 100:
27 self . grades . append ( grade )
28 return True
29 return False
30
31 def ca lculat e_aver age ( self ) :
3
Python Programming Fundamentals George Mugala - Copperbelt University
1 class UniversityCourse :
2 " " " Class demonstrating class and static methods " " "
3
4 total_courses = 0
5
6 def __init__ ( self , code , name , credits ) :
7 self . code = code
8 self . name = name
9 self . credits = credits
10 UniversityCourse . total_courses += 1
11
12 @classmethod
13 def c re at e_ fr om _s tr in g ( cls , course_string ) :
14 " " " Class method to create course from string " " "
15 code , name , credits = course_string . split ( " ," )
16 return cls ( code . strip () , name . strip () , int ( credits ) )
17
18 @staticmethod
19 def is_valid_credits ( credits ) :
20 " " " Static method to validate credits " " "
21 return 1 <= credits <= 6
22
23 @classmethod
24 def ge t_tota l_cour ses ( cls ) :
25 " " " Get total number of courses created " " "
26 return cls . total_courses
27
28 # Using class method
29 course_str = " CS101 , Introduction to Programming , 3 "
30 course1 = UniversityCourse . cre at e_ fr om _s tr in g ( course_str )
31 print ( f " Course : { course1 . name } ({ course1 . code }) " )
32
33 # Using static method
34 print ( f " Are 5 credits valid ? { UniversityCourse . is_valid_credits (5) } " )
4
Python Programming Fundamentals George Mugala - Copperbelt University
35
1 class BankAccount :
2 " " " Bank account class demonstrating encapsulation " " "
3
4 def __init__ ( self , account_holder , initial_balance =0) :
5 self . account_holder = account_holder
6 self . __balance = initial_balance # Private attribute
7 self . _ _ t r a n s a c t i o n _ h i s t o r y = []
8
9 @property
10 def balance ( self ) :
11 " " " Getter for balance " " "
12 return self . __balance
13
14 @balance . setter
15 def balance ( self , amount ) :
16 " " " Setter for balance with validation " " "
17 if amount < 0:
18 print ( " Error : Balance cannot be negative " )
19 else :
20 self . __balance = amount
21
22 def deposit ( self , amount ) :
23 " " " Deposit money into account " " "
24 if amount > 0:
25 self . __balance += amount
26 self . _ _ t r a n s a c t i o n _ h i s t o r y . append ( f " Deposited : ZMW { amount } "
)
27 return True
28 return False
29
30 def withdraw ( self , amount ) :
31 " " " Withdraw money from account " " "
32 if 0 < amount <= self . __balance :
33 self . __balance -= amount
34 self . _ _ t r a n s a c t i o n _ h i s t o r y . append ( f " Withdrew : ZMW { amount } " )
35 return True
36 print ( " Insufficient funds or invalid amount " )
37 return False
38
39 def g e t _ t r a n s a c t i o n _ h i s t o r y ( self ) :
40 " " " Get transaction history ( read - only ) " " "
41 return self . _ _ t r a n s a c t i o n _ h i s t o r y . copy () # Return copy for
encapsulation
42
43 # Using encapsulated class
44 account = BankAccount ( " John Banda " , 1000)
45 print ( f " Initial Balance : ZMW { account . balance } " )
46
47 account . deposit (500)
5
Python Programming Fundamentals George Mugala - Copperbelt University
1.5 Inheritance
1 class Person :
2 " " " Base class for all persons " " "
3
4 def __init__ ( self , name , age , gender ) :
5 self . name = name
6 self . age = age
7 self . gender = gender
8
9 def introduce ( self ) :
10 return f " Hello , I ’m { self . name } , { self . age } years old . "
11
12 def display_info ( self ) :
13 print ( f " Name : { self . name } " )
14 print ( f " Age : { self . age } " )
15 print ( f " Gender : { self . gender } " )
16
17 class Student ( Person ) :
18 " " " Student class inheriting from Person " " "
19
20 def __init__ ( self , name , age , gender , student_id , course ) :
21 # Call parent class constructor
22 super () . __init__ ( name , age , gender )
23 self . student_id = student_id
24 self . course = course
25 self . enrolled_courses = []
26
27 # Method overriding
28 def display_info ( self ) :
29 super () . display_info ()
30 print ( f " Student ID : { self . student_id } " )
31 print ( f " Course : { self . course } " )
32
33 def enroll_course ( self , course ) :
34 " " " Enroll in a course " " "
35 if course not in self . enrolled_courses :
36 self . enrolled_courses . append ( course )
37 return True
38 return False
39
6
Python Programming Fundamentals George Mugala - Copperbelt University
1 class Researcher :
2 " " " Mixin class for research capabilities " " "
3
4 def conduct_research ( self , topic ) :
5 return f " Conducting research on { topic } "
6
7 def publish_paper ( self , title , journal ) :
8 return f " Published ’{ title } ’ in { journal } "
9
10 class Teacher :
11 " " " Mixin class for teaching capabilities " " "
12
13 def prepare_lecture ( self , topic ) :
14 return f " Preparing lecture on { topic } "
15
16 def grade_assignment ( self , student , marks ) :
7
Python Programming Fundamentals George Mugala - Copperbelt University
1.7 Polymorphism
8
Python Programming Fundamentals George Mugala - Copperbelt University
9
Python Programming Fundamentals George Mugala - Copperbelt University
1 class Vector :
2 " " " Vector class demonstrating special methods " " "
3
4 def __init__ ( self , x , y ) :
5 self . x = x
6 self . y = y
7
8 # String representation
9 def __str__ ( self ) :
10 return f " Vector ({ self . x } , { self . y }) "
11
12 def __repr__ ( self ) :
13 return f " Vector ( x ={ self . x } , y ={ self . y }) "
14
15 # Arithmetic operations
16 def __add__ ( self , other ) :
17 return Vector ( self . x + other .x , self . y + other . y )
18
19 def __sub__ ( self , other ) :
20 return Vector ( self . x - other .x , self . y - other . y )
21
22 def __mul__ ( self , scalar ) :
23 return Vector ( self . x * scalar , self . y * scalar )
24
25 # Comparison operators
26 def __eq__ ( self , other ) :
27 return self . x == other . x and self . y == other . y
28
29 def __lt__ ( self , other ) :
30 # Compare magnitudes
31 return ( self . x **2 + self . y **2) < ( other . x **2 + other . y **2)
32
33 # Length / magnitude
34 def __len__ ( self ) :
35 return 2 # Always 2 D vectors
36
37 def magnitude ( self ) :
38 return ( self . x **2 + self . y **2) ** 0.5
39
40 # Container emulation
41 def __getitem__ ( self , index ) :
42 if index == 0:
43 return self . x
44 elif index == 1:
45 return self . y
46 else :
47 raise IndexError ( " Vector index out of range " )
48
49 def __setitem__ ( self , index , value ) :
50 if index == 0:
51 self . x = value
52 elif index == 1:
53 self . y = value
54 else :
55 raise IndexError ( " Vector index out of range " )
56
10
Python Programming Fundamentals George Mugala - Copperbelt University
15 @abstractmethod
16 def get_details ( self ) :
17 " " " Return detailed information " " "
18 pass
19
20 def common_method ( self ) :
21 " " " Common method for all university members " " "
22 return f " { self . name } ( ID : { self . id_number }) is a { self . get_role
() } "
23
24 class ConcreteStudent ( UniversityMember ) :
25 " " " Concrete implementation of Student " " "
26
27 def __init__ ( self , name , id_number , course ) :
28 super () . __init__ ( name , id_number )
29 self . course = course
30
31 def get_role ( self ) :
32 return " Student "
33
34 def get_details ( self ) :
35 return f " Student : { self . name } , Course : { self . course } "
36
37 class ConcreteLecturer ( UniversityMember ) :
38 " " " Concrete implementation of Lecturer " " "
39
40 def __init__ ( self , name , id_number , department ) :
11
Python Programming Fundamentals George Mugala - Copperbelt University
1 class Engine :
2 " " " Engine class for composition example " " "
3
4 def __init__ ( self , horsepower ) :
5 self . horsepower = horsepower
6
7 def start ( self ) :
8 return " Engine started "
9
10 def stop ( self ) :
11 return " Engine stopped "
12
13 class Wheels :
14 " " " Wheels class for composition example " " "
15
16 def __init__ ( self , count ) :
17 self . count = count
18
19 def rotate ( self ) :
20 return f " { self . count } wheels rotating "
21
22 class Car :
23 " " " Car using composition ( has - a relationship ) " " "
24
25 def __init__ ( self , model , engine_hp , wheel_count =4) :
26 self . model = model
27 self . engine = Engine ( engine_hp ) # Composition
28 self . wheels = Wheels ( wheel_count ) # Composition
29
12
Python Programming Fundamentals George Mugala - Copperbelt University
32
O - Open/Closed Principle Classes should be open for extension but closed for mod-
ification.
1 class Discount :
2 def calculate ( self , amount ) :
3 pass
4
5 class StudentDiscount ( Discount ) :
6 def calculate ( self , amount ) :
7 return amount * 0.8 # 20% discount
8
9 class StaffDiscount ( Discount ) :
13
Python Programming Fundamentals George Mugala - Copperbelt University
1 """
2 University Management System
3 Comprehensive OOP example for CBU
4 """
5
6 class Person :
7 def __init__ ( self , name , email , phone ) :
8 self . name = name
9 self . email = email
10 self . phone = phone
11
12 def contact_info ( self ) :
13 return f " Email : { self . email } , Phone : { self . phone } "
14
15 class Student ( Person ) :
16 def __init__ ( self , name , email , phone , student_id , year ) :
17 super () . __init__ ( name , email , phone )
18 self . student_id = student_id
19 self . year = year
20 self . courses = []
21
22 def enroll_course ( self , course ) :
23 self . courses . append ( course )
24
25 def get_transcript ( self ) :
26 return f " Transcript for { self . name } ({ self . student_id }) "
27
28 class Lecturer ( Person ) :
29 def __init__ ( self , name , email , phone , employee_id , department ) :
30 super () . __init__ ( name , email , phone )
31 self . employee_id = employee_id
32 self . department = department
33
34 def assign_grade ( self , student , course , grade ) :
35 return f " Assigned grade { grade } to { student . name } for { course } "
36
37 class Course :
38 def __init__ ( self , code , name , credits ) :
39 self . code = code
40 self . name = name
41 self . credits = credits
42 self . students = []
43 self . lecturer = None
14
Python Programming Fundamentals George Mugala - Copperbelt University
44
15
Python Programming Fundamentals George Mugala - Copperbelt University
100
16
Python Programming Fundamentals George Mugala - Copperbelt University
4 Updated Assessment
4.1 Continuous Assessment (40%)
Weekly quizzes (10%)
6. Document your classes: Use docstrings for each class and method
7. Follow naming conventions: CamelCase for classes, snake case for methods
17