Python OOP Exercises for Beginners
Python OOP Exercises for Beginners
Chapter 2
Exercise 2.
1. Define a Python class named 'Time' defined by instance variables to store the hours,
hours:minutes:seconds. Example: (12:32:45).
2. Create an object of type Time.
3. Create a function show_time(t) that is used to visualize the attributes of an object of the Time class.
4. Redefine the method affiche_heure (self), inside the class Time. The first parameter "self" is
mandatory, because it represents the instance to which the method will be associated.
5. Create an object of type Time now and test the new method on this object.
Exercise 3.
Define a BankAccount class (), which allows the instantiation of objects such as account1, account2, etc.
The constructor of this class will initialize two attributes name and balance, with the default values 'Salim' and 1000.
Three other methods will be defined:
[Link](self, somme) will allow to add a certain amount to the balance;
[Link](self, somme) will allow to withdraw a certain amount from the balance;
c.__repr__(self) will display the name of the account holder and the balance of their account.
a1 = Car('Peugeot', 'blue')
>>> a2 = Voiture(couleur='verte')
a3 = Car('Mercedes')
>>> a1 = Car('Peugeot', 'blue')
>>> a1.driver_choice("Ramzi")
>>> a2.driver_choice("Safa")
>>> [Link](1.8, 12)
[Link](1.9, 11)
This car has no driver
>>> a2.display_all()
Ford driven by Safa, speed = 21.6 m/s
>>> a3.display_all()
Red Mercedes driven by no one, speed = 0 m/s
>>> print(a3)
Red Mercedes driven by no one, speed = 0 m/s
Exercise 5.
Classes are often used to model objects in the real world. We can represent
the data about a person in a program through a Person class, containing the person's name,
his name, his phone number, and his email. A __str__ method can print the data of the
nobody.
Examples:
>>> amir = Personne('Ben Salem', 'Amir', '55593581', "amirbs@[Link]")
>>> print(amir)
Ben Salem, Amir -- Telephone: 55593581 -- Email: "amirbs@[Link]"
>>> mariem = Personne('Abassi', 'Mariem', '55519403',"mariem12@[Link]")
>>> print(mariem)
Abassi, Mariem -- Telephone : 55519403 -- Email :"mariem12@[Link]"
Work to do: Implement the Person class.
A scientist is a special type of worker. The Scientist class can thus be derived from the class
Worker. Add data on the scientific discipline (physics, chemistry, mathematics,
computer science, ...). One can also add the type of scientist: theoretical, experimental, or computational. The
the value of such a type attribute should not be limited to a single category, as a scientist can be
classified as, for example, both experimental and computer-based (that is, you can represent the
value in the form of a list or a tuple.
Work to be done: Implement the Scientist class.
4. Finally, create a main demonstration program where you create and print instances of classes.
Person, Worker and Scientist. Print the content of the attributes of each instance.
Exercise 6.
In this exercise, you will build an address book using the Person class defined in the
the previous exercise to record your contacts (friends, family, ...). Each entry in the address book will be
an instance of the Person class.
The address book should allow you to search for and return information about your contacts.
Work to be done:
Create a class AddressBook containing the following methods:
1. The constructor method __init__
2. The __str__ printing method
3. A method called add_contact that allows you to add a person to your address book.
4. A method search_contact that searches for a contact by their name among the registered people in
your address book and display in a new line each contact with the specified name. This
method must accept two arguments:
• A mandatory argument: the name of the contact to search.
• A second optional argument: the contact's first name, allowing to narrow down the result if there are multiple.
contacts have the same name.
This is an example that shows you how your class should work after the implementation of these two.
methods.
For example, your address book contains the entries 'Ali Ben Salem' and his sister 'Sana Ben Salem':
>>> a = AddressBook()
>>> a.add_contact(Person('Ben Salem', 'Ali', ... ))
>>> a.add_contact(Person('Ben Salem', 'Sana', ... ))
>>> a.find_contact('Ben Salem')
Ben Salem, Ali -- Telephone : ...
Ben Salem, Sana -- Telephone : ...
>>> a.search_contact('Ben Salem', 'Ali')
Ben Salem, Ali -- Telephone : ...
Exercise 8:
Let's program a class Vector2d whose objects will model vectors with two real components in a
orthonormal frame (O ; I ; J), graduated with the same unit (OI = OJ = 1 unit). When the mathematician says: "
Let it be the vector ⃗ (3,-2), the Python programmer will say: "u = Vect2d(3,-2)".
1. Program the constructor, responsible for initializing the attributes x and y of the current instance, which is named
By default, x and y will be set to 0.
If I want to add two vectors, I have two solutions. Either I program a mathematical function.
add(v1,v2) outside the class. Or, in a pure object-oriented programming perspective, I
addProgram as an instance method inside the class. Adopt this second solution, for
which the result of the addition with the method will be a new vector.
Exercise 9:
In this exercise, we are interested in creating classes to manage the flights of a local airline that
Organize flights between cities. More specifically, we will focus on flight plans between different cities.
Here are the available flights along with the departure time.
1. To create a DirectFlight class that will represent a direct flight between two cities (no layover in a city
intermediate), we must:
[Link] the constructor of this class that has four attributes:
• depetarrqui designates respectively the departure city and the arrival city
• day refers to the day of the week (Monday, Tuesday, ... )
• hour (an integer between 0 and 24 representing the departure time)
2. Create a class Flights that will represent all the flights throughout the week using the Direct_Flight class.
To do this, we must:
2.1. Define the constructor of this class with a single attribute that is a list of flights.
2.2. Write a method List_successors that returns a list containing the destination cities from a city of
departure passed as parameter
2.3. Write a method called Belongs that checks whether a city is part of the flight plan, whether as
city of arrival or departure
2.4. Write a methodDisplaythat shows all direct flights
We propose to build the class PolynomeCreux with real coefficients, the skeleton (to be completed) of which is defined
by :
class PlynomeCreux :
Manipulation of single-variable sparse polynomials
def __init__(self):
[Link] = {} # initialization to a null polynomial
def degree(self):
#réponse à la question 2
⁞
def primitive(self):
#réponse à la question 7
⁞
Requested work:
Question 1 :
Complete the script of the method add_monome. It is reminded that this method adds a monomial entered to
keyboard (after performing the necessary checks) if the parameter monome is null or add the monomial named monome
otherwise.
Question 2 :
Write the script for the method named degree, which returns the degree of the polynomial.
Question 3:
Write the script for the method named __call__ which returns the value of the polynomial for a given real x0.
Question 4 :
Write the script of the method named __add__, which returns the sum polynomial of two polynomials. Note
no null monomial should appear in the resulting polynomial.
Question 5:
Write the script for the method named __mul__, which returns the product polynomial of two polynomials.
Note: no zero monomial should appear in the resulting polynomial.
Question 6 :
Write the script for the method named __str__, which returns the string representing the expression of the polynomial.
ordered in descending order.
For the polynomial represented by { 4:4, 0:4 , 12:6 , 9:1 , 7 :-1}, the returned string is: "6*x**12 + x**9 - x**7"
+ 4*x**4 + 4
Question 7 :
Write the script of the method, named primitive, which returns the polynomial representing the primitive. It is assumed
that the constant of integration is zero.
Question 8 :
The integral of a hollow polynomial P in x between the limits a and b is defined by: =∫
Write the script for the function named 'integrale' that returns the value of S from a polynomial.
P, of type SparsePolynomial, and integration limits a and b real.