Python Mortgages
Python Mortgages
class Mortgage(object):
"""Abstract class for building different kinds of mortgages"""
def makePayment(self):
"""Make a payment"""
self.paid.append(self.payment)
reduction = self.payment - self.owed[-1]*self.rate
self.owed.append(self.owed[-1] - reduction)
def getTotalPaid(self):
"""Return the total amount paid so far"""
return sum(self.paid)
def str (self):
return self.legend
Looking at init , we see that all Mortgage instances will have instance variables corresponding to
the initial loan amount, the monthly interest rate, the duration of the loan in months, a list of
payments that have been made at the start of each month (the list starts with 0.0, since no payments
have been made at the start of the first month), a list with the balance of the loan that is outstanding
at the start of each month, the amount of money to be paid each month (initialized using the value
returned by the function findPayment), and a description of the mortgage (which initially has a value
of None). The init operation of each subclass of Mortgage is expected to start by calling
Mortgage. init , and then to initialize self.legend to an appropriate description of that
subclass.
The method “makePayment()” is used to record mortgage payments. Part of each payment
covers the amount of interest due on the outstanding loan balance, and the remainder of the
payment is used to reduce the loan balance. That is why “makePayment()” updates both
self.paid and self.owed.
The method “getTotalPaid()” uses the built-in Python function sum, which returns the sum
of a sequence of numbers. If the sequence contains a non-number, an exception is raised.
Above Code contains classes implementing two types of mortgage.
Each of these classes overrides init and inherits the other three methods from
Mortgage.
Above Code contains a third subclass of Mortgage. The class TwoRate treats the
mortgage as the concatenation of two loans, each at a different interest rate. (Since
self.paid is initialized with a 0.0, it contains one more element than the number of
payments that have been made. That’s why makePayment compares
len(self.paid) to self.teaserMonths + 1).
Above Code contains a function that computes and prints the total cost of each kind of
mortgage for a sample set of parameters. It begins by creating one mortgage of each kind.
It then makes a monthly payment on each for a given number of years. Finally, it prints
the total amount of the payments made for each loan.