Having reached the halfway mark of the course, it is a more than opportune time to review the major concepts of object-oriented programming. Object-oriented programming can be broadly defined as programming through the use of 'objects' containing both data and methods. Broadly speaking, these objects are instances of classes which contain methods through which each object (aka 'self') can be modified.
The major concepts we have learned thus far concern classes and inheritance, recursion, and abstract data types (ADT's). We briefly review each major concept:
(1) Classes & Inheritance
A class essentially is a blueprint for the creation of an object, which is itself an instance of the class. Below is the code for a parent class named Employee. We analyze its components.
class Employee():
"""
An employee.
eid: int - This employee's ID number
name: str - This employee's name
SIN: int - This employee's social insurance number
pay_period: str - This employee's pay period, either 'weekly' or
'monthly'
This is an abstract class. Only child classes should be instantiated.
"""
def __init__(self, eid, name, SIN, pay_period):
"""
(Employee, int, str, int, str) -> NoneType
"""
self.eid = eid
self.name = name
self.SIN = SIN
self.pay_period = pay_period
self.pay_history = {}
def amount_of_pay(self):
"""
(Employee) -> float
Return the amount that this Employee should be paid in the next
pay period.
"""
raise NotImplementedError('Implemented in a subclass')
def record_pay(self, date):
"""
(Employee, str) -> NoneType
Record the amount this Employee should be paid for the next pay
period in their pay history, with the associated date.
"""
amount = self.amount_of_pay()
self.pay_history[date] = amount
def total_pay(self):
"""
(Employee) -> float
Return the total amount of pay this Employee has received.
"""
return sum([amount for (day, amount) in self.pay_history.items()])
The parent class serves to encapsulate the salient properities that are common to ALL subclasses. As such, record_pay and total_pay are implemented in the parent class using of course arguments obtained from the child class (as seen in amount_of_pay). In addition, the __init__ contains each employee's SID, name, and eid since ALL employess are characterized by these features regardless of their subclassification. As a final point, methods that the parent class cannot complete contain a 'raise NotImplementedError' to signify that these methods are to be executed in the subclass.
(2) Recursion
Recursion is the esentially the use of repeated sub-problems to solve one larger problem. In other words, recursive methods or functions call upon themselves a certain number of times, 'reducing' the overall problem to a 'base case' for which an assigned value can be given. This is why most recursive functions have an if and else statement where the 'if' serves as the base case scenario and the 'else' is responsible for propelling the recursive process forward until the base case is acheived. We demonstrate this process with the following code:
def length(L):
'''
(list or non-list) -> int
Return 0 if L is not a list, or the maximum of len(L)
and the lengths of L's non-empty sublists.
Assume: L is a non-list, or a non-empty list
>>> length(17)
0
>>> length([1, [2, 3, 4, 5], 6])
4
>>> length([1, [2, 3, [4, 5]], 6])
3
'''
if isinstance(L, list):
a = max([(length(x)) for x in L])
return max(len(L), a)
else:
return 0
Here we have two cases. If L is not a list, we assign 0 (our base case). If L is a list, then we must return the max length of the sub-lists in L (including L itself). So if L is a list of 3 elements, and one of those elements is a list of 4, we would return 4 (not 3). Similarly, if L is a list of 10 integers, we would return 10 since no inner elements are themselves lists (and hence would be assigned 0 by the base case). Analysing the 'if' clause, we can see a few things: Firstly, if L is a list, the clause executes and we create a variable a which gives the max([length(x) for x in L]). So, for each element x in L, length(x) is called, executing the recursion. This value is then compared with the length of L itself to determine if either L is the longest list or if there exists a nested list inside L which is longer.
(3) ADT's (stacks, queues, trees)
Stacks and queues are data structures that essentially work in inverse manners. A stack contains a list of items or objects in which each new item to be 'pushed' (or added) is placed on top of the previous ones. As such, it is a 'last in first out' system since the last item on top will be the first to be 'popped' or removed. Queues function in the opposite manner so that the first item in is the first item out ('first in, first out'). Adding to a queue (or enqueue) adds to the end of the list while dequeuing (removing from a queue) takes away the first item in the list.
The last item to discuss is trees. Trees are characetrized by nodes which contain 'data' that the user needs. Except for the root or first node, all other nodes have a single parent node and possibly several children nodes (unless the node is a leaf in which case it is the final 'level' in the tree). We provide one example of recursion in a Tree class to conclude. Here is the code for finding the height (or number of levels of nodes in a tree):
def height(t):
''' (Tree) -> int
Return height of Tree t,
>>> tn2 = Tree(2, [Tree(4), Tree(4.5), Tree(5), Tree(5.75)])
>>> tn3 = Tree(3, [Tree(6), Tree(7)])
>>> tn1 = Tree(1, [tn2, tn3])
>>> height(tn1)
3
'''
if t.children:
return max([height(c) for c in t.children]) + 1
else:
return 1
This code asks each successive group of children nodes for their height and passes this information on, accumulating +1 for each level until the root node is reached at which point the 'else' statement executes adding +1 to the final answer.
Overall, trees have proven to be an interesting and rather complex concept that I hope to work more with in order to better integrate my understanding of recursion and abstract data types in general.
No comments:
Post a Comment