2024_25_COL100_Lab_11_Class_Object (1)
2024_25_COL100_Lab_11_Class_Object (1)
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.
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 ()
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.
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
• 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.
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)
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).
Perimeter = 2 × (5 + 10) = 30
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
• balance (float)
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’.
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.
Page 9
• multiply(a, b): Returns the result of a multiplied by b.
• events: A dictionary where keys are dates (in the format YYYY-MM-DD) and values
are lists of event descriptions.
Page 10
• add event(date, event): Adds an event to the specified date.
• get all events(): Returns a dictionary of all events scheduled across all dates.
Ensure that no duplicate events are added for the same date.
• 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.
Page 11
• move(from position, to position): Moves a piece from one position to another
if the move is valid.
• get valid moves(position): Returns a list of all valid moves for a piece from the
given position.
• 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).
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
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
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 14