In Python, functions *are* objects! The example code, therefore, can be written this way:
def loony():
print "You're a loony."
def newBrain():
print "You might even need a new brain."
def afford():
print "I couldn't afford a whole new brain."
# An object that holds commands:
class Macro:
def __init__(self):
self.commands = []
def add(self, command):
self.commands.append(command)
def __call__(self):
for c in self.commands:
c()
macro = Macro()
macro.add(loony)
macro.add(newBrain)
macro.add(afford)
macro()
This deserves more than a passing mention! I think it is quite important. For example, it is common to say:
def byName(rec1, rec2):
""" Comparator function to sort records by name """
return cmp(rec1.name, rec2.name)
recordList.sort(byName)
Here we pass a "function object", in the most literal sense, as a Strategy to the sort() method.
kitano@usa.com
Looking for the full Paris Hilton experience? Then look no further! YEP were talking about the Paris Hilton Sex.The home of truth video tape at parishiltonthesex.tblog.com