Thursday, February 25, 2010

Python - a simple polymorphism example

# A quick example of polymorphism at work in python 
class Food(object):
    def __init__(self, name, calories): = name
        self.calories = calories
    def tastesLike(self):
        raise NotImplementedException("Subclasses are responsible for creating this method")
class HotDog(Food):
    def tastesLike(self):
        return "Extremely processed meat" 
class Hamburger(Food):
    def tastesLike(self):
        return "grilled goodness" 
class ChickenPatty(Food):
    def tastesLike(self):
        return "tastes like chicken" 
dinner = []
dinner.append(HotDog('Beef/Turkey BallPark', 230))
dinner.append(Hamburger('Lowfat Beef Patty', 260))
dinner.append(ChickenPatty('Micky Mouse shaped Chicken Tenders', 170))
# even though each course of the dinner is a differnet type 
# we can process them all in the same loop 
for course in dinner:
    print + " is type " + str(type(course))
    print "  has " + str(course.calories) + " calories " 
    print "  and tastes like " + course.tastesLike()
# my output: 
#Beef/Turkey BallPark is type <class '__main__.HotDog'> 
#  has 230 calories 
#  and tastes like Extremely processed meat 
#Lowfat Beef Patty is type <class '__main__.Hamburger'> 
#  has 260 calories 
#  and tastes like grilled goodness 
#Micky Mouse shaped Chicken Tenders is type <class '__main__.ChickenPatty'> 
#  has 170 calories 
#  and tastes like tastes like chicken 

1 comment: