2024_25_COL100_Lab_12_Object_Oriented_Programming
2024_25_COL100_Lab_12_Object_Oriented_Programming
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.
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.
• 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.
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.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
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
12 b i r d = Bird ( )
13 dog = Dog ( )
14
Page 4
1.3.1 Problem Statement
Create a restaurant ordering system, where you can be able to perform below mentioned
tasks:
• 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
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
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.
• Once you’re confident your code is correct, submit the main.py file to the Grade-
scope assignment.
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
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
• 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?
• 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:
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.
• events: A dictionary where keys are dates (in the format YYYY-MM-DD) and values
are lists of event descriptions.
• get all events(): Returns a dictionary of all events scheduled across all dates.
Ensure that no duplicate events are added for the same date.
Page 12
3.3 Chess Game
3.3.1 Problem Statement
Create a class-based implementation for a simple chess game.
• 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.
• get valid moves(position): Returns a list of all valid moves for a piece from the
given position.
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
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
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
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