# A quick example of polymorphism at work in python class Food(object): def __init__(self, name, calories): self.name = 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 course.name + " 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
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Showing posts with label type. Show all posts
Showing posts with label type. Show all posts
Thursday, February 25, 2010
Python - a simple polymorphism example
Labels:
inheritance,
object,
polymorphism,
string,
type
Wednesday, September 16, 2009
Python - determine an image's type (regardless of extension)
# iterate through all the files in the current directory # identify the type of image file (regardless of extension) import os import imghdr # list files in the current working directory for f in os.listdir('.'): if os.path.isfile(f): imgtype = imghdr.what(f) if imgtype is None: imgtype = "not image" print "'" + f + "'" + " is type " + imgtype #output: (for me) #'2007 Oct 31 146.jpg' is type jpeg # #'2007 Oct 31 147.jpg' is type jpeg # #'2007 Oct 31 148.jpg' is type jpeg # #'2007 Oct 31 149.image' is type jpeg # #'2007 Oct 31 150.jpg' is type jpeg # #'big kitty.GI' is type gif # #'eric.image' is type jpeg # #'LICENSE.txt' is type not image # #'NEWS.txt' is type not image #
Subscribe to:
Posts (Atom)