Programmation Orientée Objet - Exercices

Exercice de POO avec Python
Author

Ludovic Deneuville

1 Setup

1.1 Start a VSCode service

1.2 Retrieve the code

There are two possibilities to retrieve the code:

  • clone the teacher’s repository directly
    • git clone https://github.com/ludo2ne/ENSAI-2A-remise-a-niveau.git
  • create a fork of this repository, then clone this fork
    • https://github.com/ludo2ne/ENSAI-2A-remise-a-niveau/fork{target=“_blank”}
    • git clone https://$GIT_PERSONAL_ACCESS_TOKEN@github.com/<username>/ENSAI-2A-remise-a-niveau.git

If you clone the teacher’s repository directly, you will not be able to use Git to keep track of your work. You will have to download the files manually, for example.

A fork is a copy of a remote repository. Since this copy belongs to you, you have the right to modify the code.

Then, go to the src/POO folder:

    • or directly from the terminal: code-server /home/onyxia/work/ENSAI-2A-remise-a-niveau/src/Python-POO/

You can then code in the files in the exercise folder. If needed, you can create new files.

2 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 execute this file, this code will be run.

class Point:

    # ...

if __name__ == "__main__":
    p1 = Point(1, 2)
    p2 = Point(1, 2)
    print(f"p1 : {p1}")
    print(f"Distance between p1 and p2 : {p1.distance(p2)}")
    print(f"p1 is equal to p2 : {p1 == p2}")

3 Exercise 2 - Polygons

    • We will assume from now on that segments do not cross
    • these methods will be defined in child classes
    • check the number of points each time

Here is the class diagram generated with Mermaid

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()
    }

4 Exercise 3 - Domino

4.1 A Domino

Write a Domino class with:

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

Exercise 3