Skip to content
Snippets Groups Projects
Commit 90fe84d5 authored by Brady James Garvin's avatar Brady James Garvin
Browse files

Added more examples of method overriding, polymorphism, and duck typing.

parent 03240594
Branches
Tags
No related merge requests found
class Patient(object):
def __init__(self, name, region, age):
self.name = name
self.region = region
self.age = age
def __repr__(self):
return f'Person({repr(self.name)}, {repr(self.region)}, {repr(self.age)})'
class Cohort(object):
def includes(self, patient):
raise NotImplementedError('The Cohort class\'s includes method must be overridden to be called.')
def filter(self, patients):
result = []
for patient in patients:
if self.includes(patient):
result.append(patient)
return result
class RegionalCohort(Cohort):
def __init__(self, region):
self.region = region
def includes(self, patient):
return patient.region == self.region
class AgeCohort(Cohort):
def __init__(self, minimum, maximum):
self.minimum = minimum
self.maximum = maximum
def includes(self, patient):
return self.minimum <= patient.age <= self.maximum
if __name__ == '__main__':
ada = Patient('Ada', 'UK', 203)
charles = Patient('Charles', 'UK', 227)
grace = Patient('Grace', 'US', 112)
patients = [ada, charles, grace]
uk_cohort: Cohort = RegionalCohort('UK')
young_cohort: Cohort = AgeCohort(0, 225)
print(f'Charles is in the UK region: {uk_cohort.includes(charles)}')
print(f'Charles is in the "young" age group: {young_cohort.includes(charles)}')
print(f'Everyone in the UK region: {uk_cohort.filter(patients)}')
print(f'Everyone in the "young" age group: {young_cohort.filter(patients)}')
notes.py 0 → 100644
class Visit(object):
def __init__(self):
self.notes = []
def add_note(self, note):
self.notes.append(note)
class Appointment(object):
def __init__(self):
self.note = None
def add_note(self, note):
self.note = note
def void(event):
event.add_note('Voided.')
if __name__ == '__main__':
visit = Visit()
appointment = Appointment()
number = 7
void(visit)
print(visit.notes)
void(appointment)
print(appointment.note)
void(number)
...@@ -9,6 +9,9 @@ class Patient(Person): ...@@ -9,6 +9,9 @@ class Patient(Person):
if __name__ == '__main__': if __name__ == '__main__':
print(object()) example_object: object = object()
print(Person()) example_person: object = Person()
print(Patient()) example_patient: object = Patient()
print(example_object)
print(example_person)
print(example_patient)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment