Main Content

Python - a truly dynamic language

Archive - Originally posted on "The Horse's Mouth" - 2009-01-30 17:18:13 - Graham Ellis

In Python everything is an object - and that includes functions which are objects which contain blocks of code. And this means that you can define different functions of the same name depending on a condition, and you can replace a function with another one too, if you want to.

This really is valid:

ontop = int(raw_input("Enter 1 if summat ontop "))
 
if ontop == 1:
  def tanksize(basedim):
    vlume = basedim * (basedim+1) * (basedim+2)
    return vlume
else:
  def tanksize(basedim):
    vlume = basedim * (basedim+2)
    return vlume
 
for k in range(10):
  more = tanksize(k)
  print "more is ", more
 
def tanksize(basedim):
  vlume = basedim * (basedim+4)
  return vlume
 
for k in range(10):
  more = tanksize(k)
  print "more is now", more

Would you write code like that? Probably not - but you could well write a piece of code that embeds within another application as required, and overrides default (preloaded) code. A number of commercial applications use Python for their tailoring, and this is the mechanism they often use to provide hooks for extra code for the minority of users who want to change certain algorithms.

Illustration - delegates write a program using the topics I have just covered in my lecture on a programming course (this course on site in Germany)