Skip to content

OOP Exercises

Eduardo Correia edited this page Oct 20, 2020 · 2 revisions

Exercises

Exercise 1

Write a class Person to store someone's personal information, such as their name, age, gender and address.

The class should have a greet() method to display in a human friendly way that same information.

Extra

If you want to make this exercise more challenging, make the class receive the birthdate of the person in question and then calculate their age.

Suggestion: Use the datetime module for this.

Exercise 2

Each person should salute everyone before presenting themselves.

To achieve this, decorate the greet() method with a wrapper that will print a salution.

Exercise 3

Define a class Shape and its subclasses Triangle, Square and Circle.

It should have an area() method that calculates the shape's area based on its dimensions and stores it in an attribute (call this method in the class constructor).

Override it for each subclass, adjusting the area formula for each kind of shape.

Exercise 4

We now want to be able to sum and subtract two shapes to form a new one.

Override the + and - operators for the Shape class that returns a new Shape with the corresponding area.

Extra

A shape can't have a negative area, so raise an Exception if this occurs.