0% found this document useful (0 votes)
5 views

2024_25_COL100_Lab_11_Class_Object (1)

This document provides an introduction to classes and objects in object-oriented programming, specifically in Python. It explains the definition and usage of classes, objects, and magic methods, along with practical examples and problem statements for creating custom classes like Car, Rectangle, BankAccount, Circle, and Calculator. Additionally, it includes guidelines for implementation and practice problems to reinforce the concepts discussed.

Uploaded by

Gaud Dhruv
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)
5 views

2024_25_COL100_Lab_11_Class_Object (1)

This document provides an introduction to classes and objects in object-oriented programming, specifically in Python. It explains the definition and usage of classes, objects, and magic methods, along with practical examples and problem statements for creating custom classes like Car, Rectangle, BankAccount, Circle, and Calculator. Additionally, it includes guidelines for implementation and practice problems to reinforce the concepts discussed.

Uploaded by

Gaud Dhruv
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/ 14

COL100: Introduction to Computer Science

Lab 11: Class and Object


March 31, 2025

1 Introduction
Classes are a fundamental concept in object-oriented programming (OOP), which orga-
nizes programs around data abstractions. A class is a blueprint for creating objects that
encapsulate both data/attributes and methods to operate on that data. It allows users
to define their own types through classes. These user-defined types enable more modu-
lar, reusable, and maintainable code, just as built-in types like float and str provide
essential functionality in Python programs.

1.1 Class
A class is a template used to create objects. It defines attributes and methods that
objects created from the class will have. For example, we can define a Car class to rep-
resent cars with attributes like make, model, and year, and methods like display info
to display information about the car.
Example of a simple class definition:
1 class Car :
2 def __init__ ( self , make , model , year ) :
3 self . make = make
4 self . model = model
5 self . year = year
6
7 def display_info ( self ) :
8 print ( f " { self . year } { self . make } { self . model } " )

In this class:
• The init method initializes an object with specific values for its attributes.

• The display info method prints information about the car.

1.2 Object
An object is an instance of a class. Once a class is defined, objects can be created using
that class. For example, creating an object of the Car class:
1 my_car = Car ( " Toyota " , " Corolla " , 2021)
2 my_car . display_info ()

This will output:


1 2021 Toyota Corolla

Here, my car is an object of the Car class, and we can access its methods and attributes.
Python allows programmers to define new types using classes that are as intuitive as built-
in types. Magic methods, also known as dunder methods (double underscore methods),
enable custom implementations of built-in functions, operators, and other behaviors.
This document provides an overview of key magic methods used for infix operators.

1.3 Magic Methods


Magic methods are used to define operator behavior for custom classes. These methods
make custom classes as intuitive and usable as Python’s built-in types. Magic methods
can be implemented to customize the behavior of built-in functions such as str and len.

Table 1: Magic Methods for Operators


Operator Magic Method Description
+ add (self, other) Defines addition behavior.
− sub (self, other) Defines subtraction behavior.
∗ mul (self, other) Defines multiplication behavior.
/ truediv (self, other) Defines true division behavior.
% mod (self, other) Defines modulus behavior.
∗∗ pow (self, other) Defines exponentiation behavior.
// floordiv (self, other) Defines floor division behavior.
>> rshift (self, other) Defines right shift behavior.
<< lshift (self, other) Defines left shift behavior.
& and (self, other) Defines bitwise AND behavior.
| or (self, other) Defines bitwise OR behavior.
∧ xor (self, other) Defines bitwise XOR behavior.
== eq (self, other) Defines equality comparison behavior.
!= ne (self, other) Defines inequality comparison behavior.
< lt (self, other) Defines ”less than” comparison.
≤ le (self, other) Defines ”less than or equal to” comparison.
> gt (self, other) Defines ”greater than” comparison.
≥ ge (self, other) Defines ”greater than or equal to” compari-
son.

Example
Below is the implementation of a Toy class in Python, which demonstrates the use of
magic methods to provide class-specific behavior.
1 class Toy ( object ) :
2 def __init__ ( self ) :

Page 2
3 self . _elems = []
4
5 def add ( self , new_elems ) :
6 """ new_elems is a list """
7 self . _elems += new_elems
8
9 def __len__ ( self ) :
10 return len ( self . _elems )
11
12 def __add__ ( self , other ) :
13 new_toy = Toy ()
14 new_toy . _elems = self . _elems + other . _elems
15 return new_toy
16
17 def __eq__ ( self , other ) :
18 return self . _elems == other . _elems
19
20 def __str__ ( self ) :
21 return str ( self . _elems )
22
23 def __hash__ ( self ) :
24 return id ( self )
25
26
27 t1 = Toy ()
28 t2 = Toy ()
29 t1 . add ([1 , 2])
30 t2 . add ([3 , 4])
31 t3 = t1 + t2
32 print ( ' The value of t3 is ' , t3 )
33 print ( ' The length of t3 is ' , len ( t3 ) )
34 d = { t1 : 'A ' , t2 : 'B '}
35 print ( ' The value ' , d [ t1 ] , ' is associated with the key t1 in d . ')

Explanation

• The Toy class demonstrates the use of several magic methods:

– init : Initializes the object with an empty list elems.


– len : Returns the length of elems, enabling the use of len().
– add : Defines the + operator for combining two Toy objects.
– eq : Compares two Toy objects for equality based on their elements.
– str : Provides a string representation for the Toy object.
– hash : Defines a hash function, allowing the object to be used as a dictio-
nary key.

• Example operations:

Page 3
– Adding elements to t1 and t2 using add().
– Combining t1 and t2 to create t3 using the + operator.
– Accessing the length of t3 using len().
– Using Toy objects as keys in a dictionary.

Guidelines for Implementation


While Python allows flexibility in defining these operators, it is strongly recommended
to adhere to their conventional meanings to maintain code clarity and avoid confusion.
Table 1.3 shows the magic methods with respect to the operators with description.

Page 4
2 Submission Problem
2.1 Display Features of a Car
2.1.1 Problem Statement
Earlier in this document, we created a Car class and defined its attributes and methods.
Now the teas is to extend on it. Create a Car class that has the following attributes:

• make (string)

• model (string)

• year (integer)

• mileage (integer)

• task size (integer)

The class should have the following methods:

• display info(): Prints year, make, model and mileage.

• get mileage(): Prints the current mileage of the car in km/l.

• calculate mileage(kms): Given a new set of distance travelled, calculate mileage,


(assuming full tank). Also, update the value stored in the object. Do floor division
while calculating mileage.

Sample Input

1 3
2 Toyota Camry 2020 10 10 # make model y e a r m i l e a g e t a n k c a p a c i t y
3 c a l c u l a t e m i l e a g e 150
4 get mileage
5 display info
Output
1 15
2 2020 Toyota Camry 15
Explanation You should define the class appropriately considering the given main pro-
gram so that the given output can be printed.

Page 5
3 Practice Problems
3.1 Calculate Area and Perimeter of a Rectangle
3.1.1 Problem Statement
Create a Rectangle class with the following attributes:
• length (float)

• width (float)
The class should have the following methods:
• get area(): Returns the area of the rectangle (length * width).

• get perimeter(): Returns the perimeter of the rectangle (2 * (length + width)).

3.1.2 Test Case 1


Main Program
1 r e c t = Rectangle (5 , 10)
2 rect . get area ()
3 rect . get perimeter ()
Output
1 50
2 30
Explanation
In this test case, the input is a rectangle with length ‘5‘ and width ‘10‘. The area is
calculated as:
Area = 5 × 10 = 50
The perimeter is calculated as:

Perimeter = 2 × (5 + 10) = 30

Thus, the expected output is the area followed by the perimeter.

3.1.3 Test Case 2


Main Program
1 r e c t = Rectangle (7 , 3)
2 rect . get area ()
3 rect . get perimeter ()
Output

Page 6
1 21
2 20
Explanation
In this test case, the input is a rectangle with length ‘7‘ and width ‘3‘. The area is
calculated as:
Area = 7 × 3 = 21
The perimeter is calculated as:

Perimeter = 2 × (7 + 3) = 20

Thus, the expected output is the area followed by the perimeter.

3.2 Bank Account Operations


3.2.1 Problem Statement
Create a BankAccount class with the following attributes:

• account holder (string)

• balance (float)

The class should have the following methods:

• deposit(amount): Deposits the given amount into the account.

• withdraw(amount): Withdraws the given amount from the account if there is


enough balance.

• get balance(): Returns the current balance of the account.

3.2.2 Test Case 1


Main Program
1 a c c o u n t = BankAccount ( ” A l i c e ” , 5 0 0 . 0 )
2 account . d e p o s i t ( 2 0 0 . 0 )
3 a c c o u n t . withdraw ( 1 5 0 . 0 )
4 account . g e t b a l a n c e ( )
Output
1 550.0
Explanation

• The program creates a ‘BankAccount’ object with:

Page 7
– Account holder: “Alice”
– Initial balance: 500.0
• A deposit of 200.0 is made, updating the balance to ‘500.0 + 200.0 = 700.0’.
• A withdrawal of 150.0 is made, updating the balance to ‘700.0 - 150.0 = 550.0’.
• Thus, the expected output is the current balance: ‘550.0’.

3.2.3 Test Case 2


Main Program
1 a c c o u n t = BankAccount ( ”Bob” , 5 0 0 . 0 )
2 account . d e p o s i t ( 2 0 0 . 0 )
3 a c c o u n t . withdraw ( 8 0 0 . 0 ) # Attempting t o withdraw more than t h e
balance
Output
1 I n s u f f i c i e n t funds
Explanation
• The input creates a ‘BankAccount’ object with:
– Account holder: “Bob”
– Initial balance: 500.0
• A deposit of 200.0 is made, updating the balance to: 500.0 + 200.0 = 700.0
• A withdrawal of 800.0 is attempted, but since the balance is only 700.0, the with-
drawal fails. The program outputs: “Insufficient funds”.

3.3 Area and Circumference of a Circle


3.3.1 Problem Statement
Create a Circle class with the following attributes:
• radius (float)
The class should have the following methods:
• get area(): Returns the area of the circle (π × radius2 ).
• get circumference(): Returns the circumference of the circle (2 × π × radius).
• A class method get pi() that returns the value of π.
Then, write the program which takes the radius as input, and prints the area, circum-
ference, and the value of π.

Page 8
3.3.2 Test Case 1
Input
1 10
Output
1 314.1592653589793
2 62.83185307179586
3 3.141592653589793
Explanation
For a circle with a radius of 10, the area is calculated as π × 102 = 314.1592653589793
and the circumference is calculated as 2 × π × 10 = 62.83185307179586. The value
of π is calculated as 3.141592653589793 by dividing the circumference by the diameter
2 × 10 = 20.

3.3.3 Test Case 2


Input
1 5
Output
1 78.53981633974483
2 31.41592653589793
3 3.141592653589793
Explanation
For a circle with a radius of 5, the area is calculated as π × 52 = 78.53981633974483
and the circumference is calculated as 2 × π × 5 = 31.41592653589793. The value of π is
returned as 3.141592653589793 by dividing the circumference by the diameter 2×5 = 10.

3.4 Complex Calculator


3.4.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.

Page 9
• 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.4.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
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.5 Event Calendar


3.5.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:

Page 10
• 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.5.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”.

3.6 Chess Game


3.6.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:

Page 11
• 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.6.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.

3.7 Car Rental Management System


3.7.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:

Page 12
∗ 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).

3.7.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 )

Page 13
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 14

You might also like