Basic Object Orientated Methods#
Follow these simple OOP exercises to practice and gain confidence in coding classes.
Exercise 1#
Task:
Create a class called
Patient
.The class should contain a constructor that accepts the following parameters. The parameters should be stored in appropriately named attributes.
patient_id: int
age: int
Hints
Don’t forget to include the
self
parameter!Make sure you use correct case for the class name.
Patient
follows PEP8 guidelines whilepatient
does not!
# your code here ...
Exercise 2:#
Task:
Create a class called
Ward
Code a constructor method.
It should accept
ward_id
(int) as parameter and assign it to an attributeIt should create a new empty list attribute that will hold patients staying on the ward.
Create a method called
add_patient
. It should accept a parameter calledpatient
(that is a patient class).Create a method or property called
n_patients
. It should return the number of patients on the ward.
Hints:
Don’t forget the
self
parameter in the method!
# your code here ...
Exercise 3:#
You will now test the Ward
class by generating a number of patients and adding them to a ward object.
Task:
Code a function that first creates a
Ward
object and then adds a user specified number ofPatient
instances via theadd_patient
function.The function must return the ward object.
Test your function with 5 patients.
Hints:
You will need to design the function so that it allocates a patient an age. One option is to randomly generate an age in a given range. You could achieve this using the
random.randint()
function. E.g.
from random import randint
lower, upper = 60, 95
age = randint(lower, upper)
# your code here ...
Exercise 4:#
Task:
Now create a
Hospital
classThe class should allow the creation of new wards as well as adding a patient to a user specified ward.
The class must provide a
n_patients
method or property that returns the uptodate total of patients in the hospital.Create some test data and create a
Hospital
object. Return the total number of patients in the hospital.
# your code here ...
Exercise 5#
Task:
Let’s create a new type of patient specific to those with respiratory conditions.
The new class will also accept patient_id
and age
. You will need to create two new parameters as well: pack_yrs
and fev1
. Fyi:
A pack year is defined as twenty cigarettes smoked everyday for one year
FEV1 stands for Forced Expiratory Volumne and is a percentage measured out of 100%. Lower values are worse.
Call the class RespiratoryPatient
Hints:
You can solve this exercise by either using inheritance or composition. Compositin is a bit harder (and more code), but its more flexible and safer in practice.
# your code here ...