classDiagram
Point --o Polygon
Polygon <|-- Segment : 2
Polygon <|-- Triangle : 3
Polygon <|-- Quadrilateral : 4
Quadrilateral <|-- Rectangle
class Point{
+float x
+float y
+distance(other_point)
}
class Polygon{
+list[Point] points_list
+area()
+perimeter()
}
class Quadrilateral{
+area()
+perimeter()
}
class Segment{
+area()
+perimeter()
}
class Triangle{
+area()
+perimeter()
}
Object-Oriented Programming - Exercises
Setup
Launching a VSCode service
Creating your directory structure
-
- 💡 avoid using accents in your code, computers don’t like them very much
Whenever you are asked to create a class, you should start by creating a file with the same name.
Help
You will find some suggested solutions on the introductory OOP course page.
Here are some simple code examples if you need inspiration:
- deux_roues.py : abstract parent class representing a two-wheeled vehicle
- trottinette.py : class representing a scooter (inherits from DeuxRoues)
- velo.py : class representing a bicycle (inherits from DeuxRoues)
- main.py : a sandbox file for testing
1 Exercise 1 - Points
Define a Point class to represent a point in the plane with x and y coordinates.
Implement the following methods:
To check that your methods are correct, you can add a main block at the end of your class. When you run this file, this is the code that will be executed.
point.py
class Point:
# ...
if __name__ == "__main__":
p1 = Point(1, 2)
p2 = Point(1, 2)
print(f"p1 : {p1}")
print(f"Distance entre p1 et p2 : {p1.distance(p2)}")
print(f"p1 est égal à p2 : {p1 == p2}")2 Exercise 2 - Polygons
You will now use objects from the Point class to create more complex objects.
You will also use inheritance, i.e. reusable behaviors will be defined in the parent classes and specific behaviors in the child classes.
-
- We will assume that the segments do not intersect
-
- these methods will be defined in the child classes
-
- check the number of points each time
Here is the class diagram generated with Mermaid
3 Exercise 3 - Domino
3.1 A Domino
Write a Domino class with:
3.2 Game
Now we will try to code a domino game.
For simplicity:
- there will only be one player
- it is only possible to place a domino on one side, at the end of the domino row
Let’s start by generating all possible dominoes, i.e. all combinations from (0,0) to (6,6) without duplicates.
Write a play() function that:
classDiagram
class Domino{
+int end_A
+int end_B
+flip()
+accepts_after(other_domino)
}
Correction
Exercises 1 and 2
An example of unit tests for the Point class: