0% found this document useful (0 votes)
10 views15 pages

2024_25_COL100_Lab_12_Object_Oriented_Programming

The document provides an introduction to object-oriented programming (OOP) concepts, including classes, objects, abstraction, encapsulation, inheritance, and polymorphism, with examples in Python. It also presents a sample problem for creating a restaurant ordering system that utilizes these OOP principles. Additionally, it includes instructions for completing a LibraryBook class implementation exercise.

Uploaded by

ayushiftp14
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)
10 views15 pages

2024_25_COL100_Lab_12_Object_Oriented_Programming

The document provides an introduction to object-oriented programming (OOP) concepts, including classes, objects, abstraction, encapsulation, inheritance, and polymorphism, with examples in Python. It also presents a sample problem for creating a restaurant ordering system that utilizes these OOP principles. Additionally, it includes instructions for completing a LibraryBook class implementation exercise.

Uploaded by

ayushiftp14
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
You are on page 1/ 15

COL100: Introduction to Computer Science

Lab 12: Object-Oriented Programming


April 8, 2025

1 Introduction
1.1 Classes and Objects
In object-oriented programming (OOP), “classes” and “objects” are the building blocks of
the code structure. Understanding them is essential for writing efficient and maintainable
programs.

1.1.1 Syntax for Defining a Class in Python


Here’s the basic syntax for defining a class in Python:
1 c l a s s ClassName :
2 def i n i t ( self , attribute1 , attribute2 ) :
3 s e l f . attribute1 = attribute1
4 s e l f . attribute2 = attribute2
5

6 d e f method1 ( s e l f ) :
7 # method l o g i c h e r e
8 pass
In the above example, please note the following.

• init is the constructor method that is automatically called when an object is


created from the class. It is used to initialize the object’s attributes.

• self refers to the instance of the object being created. It allows the method to
access the attributes and methods of the specific object instance.

1.1.2 Example: Creating a Class and Object


Here’s a simple example of defining and creating an object from a class:
1 c l a s s Car :
2 def i n i t ( s e l f , make , model , y e a r ) :
3 s e l f . make = make
4 s e l f . model = model
5 s e l f . year = year
6

7 def get description ( s e l f ) :


8 r e t u r n f ”{ s e l f . y e a r } { s e l f . make} { s e l f . model } ”
9

10 # C r e a t e an o b j e c t o f t h e Car c l a s s
11 my car = Car ( ” Toyota ” , ”Camry” , 2 0 2 0 )
12

13 # A c c e s s i n g o b j e c t ' s method
14 p r i n t ( my car . g e t d e s c r i p t i o n ( ) ) # Output : ”2020 Toyota Camry”
In the above example, we do the following.

• We define a Car class with an init method to initialize its attributes (make,
model, year).

• We then create an object my car from the Car class and print its description using
the get description() method.

1.2 Object-Oriented Programming


Here, we will discuss the core concepts of object-oriented programming, i.e., abstraction,
encapsulation, inheritance, and polymorphism.

1.2.1 Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only
the essential features of an object. In Python, abstraction can be achieved by simply
defining a function. It can also be achieved by defining a class with data/attributes and
functions/methods without exposing the user to the detailed implementation.
Example:
1 c l a s s Vehicle :
2 def i n i t ( s e l f , name , max speed ) :
3 s e l f . name = name
4 s e l f . max speed = max speed
5

6 def d i s p l a y i n f o ( s e l f ) :
7 r e t u r n f ”{ s e l f . name} can go up t o { s e l f . max speed } km/h . ”
8

9 # Using t h e c l a s s
10 c a r = V e h i c l e ( ”Car” , 1 8 0 )
11 print ( car . d i s p l a y i n f o () )
Explanation
Here, the user interacts with the Vehicle class through the display info method, which
abstracts the internal details of how the data is stored (like name and max speed). The
internal data is not directly exposed, but it is made accessible through methods.

Page 2
1.2.2 Encapsulation
Encapsulation is the concept of bundling the data (attributes) and methods (functions)
into a single unit (class). It is also possible to restrict access to some of the object’s
components. This is often done using “private” and “public” access modifiers. In Python,
encapsulation is achieved by prefixing an attribute or method with a double underscore
( ), making it private.
Example:
1 c l a s s BankAccount :
2 def i n i t ( s e l f , balance ) :
3 s e l f . balance = balance # Private variable
4

5 d e f d e p o s i t ( s e l f , amount ) :
6 s e l f . b a l a n c e += amount
7

8 def get balance ( s e l f ) :


9 return s e l f . balance
10

11 # A c c e s s i n g b a l a n c e through methods
12 a c c o u n t = BankAccount ( 1 0 0 0 )
13 account . d e p o s i t (500)
14 p r i n t ( a c c o u n t . g e t b a l a n c e ( ) ) # Output : 1500
Explanation
This code demonstrates encapsulation by defining a class BankAccount that hides the
internal balance attribute and provides controlled access to it through the deposit and
get balance methods. The balance cannot be directly modified; it can only be updated
via the deposit method, ensuring secure and consistent data management.

1.2.3 Inheritance
Inheritance is a mechanism in OOP that allows a class to inherit the attributes and
methods of another class. It helps in creating a new class based on an existing class,
allowing code reuse and extension.
Example:
1 c l a s s Animal :
2 d e f speak ( s e l f ) :
3 p r i n t ( ” Animal s p e a k s ” )
4

5 c l a s s Dog ( Animal ) :
6 d e f speak ( s e l f ) :
7 p r i n t ( ”Woof” )
8

9 dog = Dog ( )

Page 3
10 dog . speak ( ) # Output : Woof
Explanation
In this example, the Dog class inherits from the Animal class. The Dog class overrides
the speak method of the Animal class to provide its own implementation, which prints
”Woof”. When an object of the Dog class calls speak(), the overridden method in Dog is
executed, demonstrating how inheritance allows the subclass (Dog) to extend and modify
the behavior of the parent class (Animal).

1.2.4 Polymorphism
Polymorphism allows methods to take on many forms. It enables a single method to
behave differently based on the object it is acting upon.
Example:
1 c l a s s Bird :
2 d e f speak ( s e l f ) :
3 p r i n t ( ”Tweet” )
4

5 c l a s s Dog :
6 d e f speak ( s e l f ) :
7 p r i n t ( ” Bark ” )
8

9 d e f make sound ( animal ) :


10 animal . speak ( )
11

12 b i r d = Bird ( )
13 dog = Dog ( )
14

15 make sound ( b i r d ) # Output : Tweet


16 make sound ( dog ) # Output : Bark
Explanation
This code demonstrates Polymorphism by using the make sound function, which can
operate on different object types (Bird and Dog) as long as they implement a speak
method. The function dynamically calls the appropriate speak method for each object,
showcasing how a common interface can handle diverse behaviors.

1.3 Sample Problem


This example demonstrates the implementation of several key object-oriented program-
ming concepts including abstraction, encapsulation, inheritance, and polymorphism.

Page 4
1.3.1 Problem Statement
Create a restaurant ordering system, where you can be able to perform below mentioned
tasks:

• Create a base class MenuItem to represent a general menu item, encapsulating


common attributes like name, price, and availability. Provide methods to retrieve
and update availability while hiding the implementation details.

• Protect sensitive data, such as the availability of menu items, by making it private.
Use getter and setter methods to control and validate access to this data.

• Extend the functionality of the MenuItem class by creating derived classes Food
and Drink. These subclasses should include additional attributes specific to their
category, such as cuisine for food and size for drinks.

• Implement a method get details() that is defined in the base class MenuItem and
overridden in the subclasses Food and Drink to provide customized details for each
type of menu item.

1.3.2 Solution

1 # Abstraction and Encapsulation : Base class for Menu Item


2 class MenuItem :
3 def __init__ ( self , name , price , item_id , available = True ) :
4 self . name = name
5 self . price = price
6 self . item_id = item_id
7 self . __available = available # Private attribute for
availability
8
9 # Encapsulation
10 # Getter and Setter for availability
11 def is_available ( self ) :
12 return self . __available
13
14 def set_availability ( self , status ) :
15 if isinstance ( status , bool ) :
16 self . __available = status
17 else :
18 print ( " Availability status must be a boolean . " )
19
20 def get_details ( self ) :
21 return f " Item : { self . name } , Price : $ { self . price :.2 f } , ID : { self
. item_id } "
22
23 # Inheritance : Derived class for Food
24 class Food ( MenuItem ) :

Page 5
25 def __init__ ( self , name , price , item_id , cuisine , available = True ) :
26 super () . __init__ ( name , price , item_id , available )
27 self . cuisine = cuisine
28

29 # Polymorphism : Overriding get_details method


30 def get_details ( self ) :
31 return ( f " Food - Name : { self . name } , Price : $ { self . price :.2 f } , "
32 f " Cuisine : { self . cuisine } , ID : { self . item_id } ,
Available : { self . is_available () } " )
33

34 # Inheritance : Derived class for Drinks


35 class Drink ( MenuItem ) :
36 def __init__ ( self , name , price , item_id , size , available = True ) :
37 super () . __init__ ( name , price , item_id , available )
38 self . size = size
39

40 # Polymorphism : Overriding get_details method


41 def get_details ( self ) :
42 return ( f " Drink - Name : { self . name } , Price : $ { self . price :.2 f } ,
"
43 f " Size : { self . size } , ID : { self . item_id } , Available : {
self . is_available () } " )
44
45 # main program
46 if __name__ == " __main__ " :
47 # Create objects for Food and Drink
48 pizza = Food ( " Pepperoni Pizza " , 15.99 , " F001 " , " Italian " )
49 coffee = Drink ( " Latte " , 4.99 , " D101 " , " Medium " )
50
51 # Display details
52 # polymorphism
53 print ( pizza . get_details () ) # Food - specific details
54 print ( coffee . get_details () ) # Drink - specific details
55
56 # Encapsulation : Check and update availability
57 print ( " Is the pizza available ? " , pizza . is_available () )
58 pizza . set_availability ( False ) # Update availability
59 print ( " Is the pizza available after update ? " , pizza . is_available () )
60

61 # inheritance
62 print ( " Drink Details : " , coffee . get_details () )

Explanation

• The MenuItem class serves as a base class that hides the implementation de-
tails of item availability using a private attribute available. Public methods
(is available and set availability) provide controlled access to this private
attribute, demonstrating encapsulation.

• The Food and Drink classes inherit attributes and methods from the MenuItem

Page 6
class, allowing them to reuse the base class functionality while adding specific
attributes like cuisine and size.

• The get details method is overridden in the Food and Drink subclasses to provide
specific implementations for each class, allowing the same method name to exhibit
different behaviors based on the object type.

• Instances of Food and Drink demonstrate the use of polymorphism through the
get details method and encapsulation by checking and updating item availability.
Inheritance is highlighted by sharing common functionality from the MenuItem
class.

Page 7
2 Submission Problem
2.1 Instructions
• Complete the code for the following problem in a file called main.py.

• Test your code using the provided test cases.

• Once you’re confident your code is correct, submit the main.py file to the Grade-
scope assignment.

• Do not change name of the functions or variables.

2.2 Problem Statement - LibraryBook Class


In this exercise, you will complete the implementation of a LibraryBook class in Python.
Below is the incomplete class definition:
1 c l a s s LibraryBook :
2

3 def i n i t ( s e l f , t i t l e : str , author : s t r ) :


4 # constructor
5 self . title = title
6 s e l f . author = author
7 s e l f . is checked out = False
8 s e l f . borrower = ””
9 s e l f . renew count = 0
10

11 def get author ( s e l f ) :


12 # r e t u r n t h e a u t h o r ' s name
13 pass
14

15 def g e t t i t l e ( s e l f ) :
16 # r e t u r n t h e book ' s t i t l e
17 pass
18

19 def get borrower ( s e l f ) :


20 # r e t u r n t h e name o f t h e b o r r o w e r o r ”NONE” i f t h e book i s
not checked out
21 pass
22

23 def get renew count ( s e l f ) :


24 # r e t u r n t h e number o f t i m e s t h e book has been renewed
25 pass
26

27 d e f c h e c k o u t ( s e l f , borrower name : s t r ) :

Page 8
28 # check out t h e book t o t h e g i v e n b o r r o w e r
29 pass
30

31 d e f renew ( s e l f ) :
32 # renew t h e book f o r t h e c u r r e n t b o r r o w e r
33 pass
34

35 def return book ( s e l f ) :


36 # r e t u r n t h e book t o t h e l i b r a r y
37 pass
38

39 def get status ( s e l f ) :


40 # r e t u r n True i f t h e book i s a v a i l a b l e f o r checkout , F a l s e
otherwise
41 pass
You need to implement the following methods:

• get author: This method should return the author’s name of the book.

• get title: This method should return the title of the book.

• get borrower: This method should return the current borrower of the book. If
the book is not checked out, it should return "NONE".

• get renew count: This method should return the number of times the book has
been renewed by the current borrower. If the book has not been checked out, it
should return 0.

• check out: This method is called when someone wants to check out the book. If
the book is already checked out, it should return -1; otherwise, it should update
the book’s status and return 1.

• renew: This method is called when the current borrower wants to renew the book.
If the book has not been checked out, return -1. If successful, increment the renew
count and return 1.

• return book: This method is called when the borrower wants to return the book.
If the book is not checked out, return -1; otherwise, return the book and return 1.

• get status: This method should return True if the book is available for checkout,
otherwise return False.

Page 9
2.2.1 Test Case
Input
1 I n v i s i b l e −Man Ralph−E l l i s o n # [ t i t l e ] [ author ] f o r the
constructor
2 author ? # calls the get author function
3 title ? # calls the g e t t i t l e function
4 bo rrow er ? # calls the get borrower function
5 check out aditya # calls the check out function ,
s e co n d word i s b o r r o w e r
6 bo rrow er ? # calls get borrower function
7 status ? # calls get status function
8 renew # calls t h e renew f u n c t i o n
9 renew count ? # calls get renew count function
10 return # calls return book function
11 status ? # calls get status function
12 END # marks t h e end o f t h e i n p u t and
t e r m i n a t e s t h e program
Output
1 Ralph−E l l i s o n
2 I n v i s i b l e −Man
3 NONE
4 1 # checkout s u c c e s s f u l
5 aditya
6 NOT AVAILABLE
7 1 # renew s u c c e s s f u l
8 1 # renewed once a f t e r b e i n g i s s u e d
9 1 # return s u c c e s s f u l
10 AVAILABLE

Additional Questions
• How do you create an object of a class in Python?

• What are public and private variables or methods in Python, and how do they
differ?

• What are the different types of constructors in Python?

• Can you think of other relevant methods or variables for this problem?

Page 10
3 Practice Problems
3.1 Complex Calculator
3.1.1 Problem Statement
Design a class Calculator that performs basic arithmetic operations and supports addi-
tional operations like exponentiation and square root. The class should encapsulate the
following private attributes:

• last result: Stores the last result computed.

The class should include the following methods:

• add(a, b): Returns the sum of a and b.

• subtract(a, b): Returns the result of a minus b.

• multiply(a, b): Returns the result of a multiplied by b.

• divide(a, b): Returns the result of a divided by b (throws an exception if b ==


0).

• exponentiate(a, b): Returns a raised to the power of b.

• squareroot(a): Returns the square root of a.

• get last result(): Returns the last computed result.

• clear(): Resets the last result to 0.

Additionally, implement polymorphism to handle operations on both integers and floating-


point numbers.

3.1.2 Test Case 1


Main Program
1 calc = Calculator ()
2 c a l c . add ( 1 0 , 5 )
3 c a l c . subtract (10 , 3)
4 c a l c . multiply (2 , 3)
5 c a l c . d i v i d e (10 , 0)
6 c a l c . exponentiate (2 , 3)
7 print ( calc . g e t l a s t r e s u l t () )
Output
1 Result : 8

Page 11
Explanation
Operations like addition, subtraction, multiplication, and exponentiation update the
result stored in last result, which can be accessed via the get last result() method.
Handling division by zero should raise an exception.

3.2 Event Calendar


3.2.1 Problem Statement
Create a class EventCalendar that manages events scheduled on different dates. The
class should have the following private attributes:

• events: A dictionary where keys are dates (in the format YYYY-MM-DD) and values
are lists of event descriptions.

The class should include the following methods:

• add event(date, event): Adds an event to the specified date.

• remove event(date, event): Removes a specific event from a specified date.

• get events(date): Returns a list of all events scheduled on a given date.

• get all events(): Returns a dictionary of all events scheduled across all dates.

• clear(): Clears all events.

• str (): Returns a string representation of the calendar.

Ensure that no duplicate events are added for the same date.

3.2.2 Test Case 1


Main Program
1 c a l e n d a r = EventCalendar ( )
2 c a l e n d a r . a d d e v e n t ( ”2024−12−01” , ” Meeting with John ” )
3 c a l e n d a r . a d d e v e n t ( ”2024−12−01” , ” C o n f e r e n c e C a l l ” )
4 c a l e n d a r . a d d e v e n t ( ”2024−12−02” , ”Team Dinner ” )
5 c a l e n d a r . r e m o v e e v e n t ( ”2024−12−01” , ” C o n f e r e n c e C a l l ” )
6 p r i n t ( c a l e n d a r . g e t e v e n t s ( ”2024−12−01” ) )
Output
1 [ ' Meeting with John ' ]
Explanation
The event “Conference Call” was removed from the list of events scheduled for “2024-
12-01”. The remaining event is “Meeting with John”.

Page 12
3.3 Chess Game
3.3.1 Problem Statement
Create a class-based implementation for a simple chess game.

• You need to represent the chessboard, pieces, and moves.

• The chessboard should be represented as an 8x8 grid, and each piece should be
represented as a subclass of a base class Piece.

• The base class should have common methods for movement and capturing, while
each piece subclass (e.g., King, Queen, Knight) should define its unique movement
logic.

The following methods should be implemented:

• move(from position, to position): Moves a piece from one position to another


if the move is valid.

• capture(piece): Captures another piece.

• get valid moves(position): Returns a list of all valid moves for a piece from the
given position.

• is checkmate() or is stalemate(): Determines if the current player is in check-


mate or stalemate.

3.3.2 Test Case 1


Main Program
1 board = ChessBoard ( )
2 k i n g = King ( )
3 queen = Queen ( )
4 board . p l a c e p i e c e ( king , ( 0 , 4 ) ) # P l a c e k i n g a t p o s i t i o n ( 0 , 4 )
5 board . p l a c e p i e c e ( queen , ( 4 , 4 ) ) # P l a c e queen a t p o s i t i o n ( 4 , 4 )
6 k i n g . move ( ( 0 , 4 ) , ( 1 , 4 ) ) # King moves
7 queen . c a p t u r e ( k i n g )
8 p r i n t ( board . i s c h e c k m a t e ( ) )
Output
1 True
Explanation
The King was captured by the Queen, resulting in a checkmate condition, which is
detected by the is checkmate() method.

Page 13
3.4 Car Rental Management System
3.4.1 Problem Statement
Design a class CarRental that manages a fleet of cars available for rent. Each car is
represented by a Car class, and customers are represented by a Customer class. The
system should support the following features:

• Attributes:
– CarRental Class:
∗ cars: A list of cars in the fleet.
∗ rented cars: A dictionary mapping customers to their rented cars.
– Car Class:
∗ car id: A unique identifier for the car.
∗ brand: Brand of the car.
∗ model: Model of the car.
∗ rental price: Price per day for renting the car.
∗ available: A boolean indicating if the car is available for rent.
– Customer Class:
∗ name: Name of the customer.
∗ customer id: A unique identifier for the customer.
∗ rented cars: A list of cars rented by the customer.
• Methods:
– CarRental Class:
∗ add car(car): Adds a new car to the fleet.
∗ remove car(car id): Removes a car from the fleet.
∗ rent car(customer, car id): Allows a customer to rent a car.
∗ return car(customer, car id): Allows a customer to return a rented
car.
∗ list available cars(): Lists all available cars for rent.
∗ list rented cars(): Lists all currently rented cars and their customers.
– Customer Class:
∗ rent car(car): Adds a car to the customer’s rented cars.
∗ return car(car): Removes a car from the customer’s rented cars.
– Inheritance: Create subclasses of Car like SUV, Sedan, and Truck, each
with unique attributes (e.g., cargo capacity for Truck, luxury rating for
Sedan).

Page 14
3.4.2 Test Case 1
Input:
1 # C r e a t e CarRental system
2 r e n t a l = CarRental ( )
3

4 # Add c a r s t o t h e f l e e t
5 c a r 1 = SUV( ”SUV001” , ” Toyota ” , ”RAV4” , 7 0 , 5 0 0 )
6 c a r 2 = Sedan ( ”SED001” , ” Mercedes ” , ”C−C l a s s ” , 1 2 0 , 5 )
7 c a r 3 = Truck ( ”TRK001” , ” Ford ” , ”F−150” , 9 0 , 1 0 0 0 )
8

9 r e n t a l . add car ( car1 )


10 r e n t a l . add car ( car2 )
11 r e n t a l . add car ( car3 )
12

13 # C r e a t e a customer
14 customer = Customer ( ” John Doe” , ”C001” )
15

16 # Rent a c a r
17 r e n t a l . r e n t c a r ( customer , ”SUV001” )
18

19 # List rented cars


20 print ( rental . list rented cars () )
21

22 # Return t h e c a r
23 r e n t a l . r e t u r n c a r ( customer , ”SUV001” )
24

25 # List available cars


26 print ( rental . l i s t a v a i l a b l e c a r s () )
Output:
1 Rented Cars :
2 John Doe : [ Toyota RAV4]
3

4 A v a i l a b l e Cars :
5 [ ' Toyota RAV4 ' , ' Mercedes C−C l a s s ' , ' Ford F−150 ' ]

Page 15

You might also like