A first demonstration of OO, including polymorphism
Archive - Originally posted on "The Horse's Mouth" - 2009-09-04 07:49:20 - Graham Ellis"Object Oriented" often means big and heavy code even for the first example application demos ... since OO works really well when you're meeting requirements beyond those which are small enough to be described as 'trivial'. So I'm very pleased with this little demonstration in Python which shows - all in one file - the definition of four different classes, the building of a list of objects of various different sorts, and then a loop that goes through all the objects using 'polymorphism' to ensure that the right accessor code is run on the right piece of data.
Scenario - monthly bills need to be multiplied by 12 for the annual cost, Council tax bills come in 10 instalments, and annual payers get a 10% discount.
class monthly:
def __init__(self,xxx):
self.val = xxx
def yearly(self):
return self.val * 12
class annual:
def __init__(self,xxx):
self.val = xxx
def yearly(self):
return self.val * 0.9
class council:
def __init__(self,xxx):
self.val = xxx
def yearly(self):
return self.val * 10
# ----------------------------
david = monthly(25)
john = monthly(14)
gerry = annual(125)
lisa = council(112)
debtors = (david, john, gerry, lisa)
for debtor in debtors:
print debtor.yearly()
Please note - this code is BELOW my minimum standards for a live application. I would expect to see comments, I would expect better variable naming, and I would use inheritance to save the need for a duplicated constructor.
Sample output:
92: grahamellis$ python accts
300
168
112.5
1120
92: grahamellis$