Main Content

Practical polymorphism in action

Archive - Originally posted on "The Horse's Mouth" - 2006-12-04 08:00:14 - Graham Ellis

Polymorphism is the ability of a piece of common code to process a piece of data in different ways depending on its type. It's a great facility, talked about a lot in theory and on courses ... but then what about its practical use? Here's a very simple little example from last week, showing how a file, another process on the computer you're using, and even a remote web page can be read in as data through the same (polymorphic) code with python's readlines method(s).

# Three ALTERNATIVE opens - just use the one you need
# from another process
from os import *
fh = popen("df -k")

# from a remote URL
import urllib
fh = urllib.urlopen("http://www.sheepbingo.co.uk")

# from a local file ...
fh = open("localfile.txt")

# ... whichever way you open your STREAM, you can readlines it!
for info in fh.readlines():
  print info,