Skip to content

OOP Exercises

Tiago Silva 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.

Solutions

Exercise 1

import datetime

class Person():
    def __init__(self, name, birthdate, gender, address):
        self.name = name
        
        birthdate = datetime.datetime.strptime(birthdate, "%Y/%m/%d")        
        days = (datetime.datetime.today() - birthdate).days
        self.age = int(days / 365.25)
        
        self.gender = gender
        self.address = address
        
    def print(self):    
        info = f"My name is {self.name}, I'm a {self.age} years old {self.gender} and I live in {self.address}."
        
        print(info)
        
p = Person("Eduardo Correia", "2000/10/10", "male", "Porto, Portugal")

# My name is Eduardo Correia, I'm a 20 years old male and I live in Porto, Portugal.
p.print()

Exercise 2

import datetime

def saudation(function):
    def wrapper(*args, **kwargs):
        print("Hello everyone, I will now present myself!")
        function(*args, **kwargs)

    return wrapper

class Person():
    def __init__(self, name, birthdate, gender, address):
        self.name = name
        
        birthdate = datetime.datetime.strptime(birthdate, "%Y/%m/%d")        
        days = (datetime.datetime.today() - birthdate).days
        self.age = int(days / 365.25)
        
        self.gender = gender
        self.address = address
    
    @saudation
    def greet(self):    
        info = f"My name is {self.name}, I'm a {self.age} years old {self.gender} and I live in {self.address}."
        
        print(info)
        
p = Person("Eduardo Correia", "2000/10/10", "male", "Porto, Portugal")

# Hello everyone, I will now present myself!
# My name is Eduardo Correia, I'm a 20 years old male and I live in Porto, Portugal.
p.greet()

Exercise 3

from math import pi

class Shape():
    def __init__(self):
        self.area = self.area()
        
    def area(self):
        return 0
    
class Triangle(Shape):       
    def __init__(self, base, height):
        self.base = base
        self.height = height
        
        Shape.__init__(self)
        
    def area(self):
        return (self.base * self.height) / 2

class Square(Shape):       
    def __init__(self, length):
        self.length = length
        
        Shape.__init__(self)
        
    def area(self):
        return self.length ** 2
    
class Circle(Shape):       
    def __init__(self, radius):
        self.radius = radius
        
        Shape.__init__(self)
        
    def area(self):
        return pi * self.radius ** 2
    
print(Triangle(2, 3).area) # 3.0
print(Square(2).area) # 4 
print(Circle(1).area) # 3.141592653589793

Exercise 4

class Shape():
    def __init__(self, area):
        self.area = area
        
    def __add__(self, s):
        area = self.area + s.area

        return Shape(area)
    
    def __sub__(self, s):
        area = self.area - s.area
        
        if (area < 0):
            raise Exception("A shape's area can't be negative.")

        return Shape(area)

print((Shape(3) + Shape(2)).area) # 5
print((Shape(3) - Shape(2)).area) # 1
print((Shape(2) - Shape(3)).area) # Exception: A shape's area can't be negative.