Is this considered black magic?
Laura Creighton
lac at strakt.com
Sun Nov 11 08:37:07 EST 2001
I want to do something which is conceptually very simple. Given a list of
objects, call make everybody call the same method you want to run. Sort
of like apply(), but for methods.
This is what I came up with:
class Ham:
def say(self):
print "I am Ham, and I don't want any arguments, thank you."
def speak_up(self, arg):
print 'I am Ham, and my arguments are %s' % arg
class Eggs:
def speak_up(self, arg='bacon'):
print 'I am Eggs, and my arguments are %s' % arg
class Spam:
def shout(self, arg1, arg2='sausage'):
print 'I AM SPAM AND MY ARGUMENTS ARE %s AND %s' % (arg1, arg2)
def foreach(name_key, object_list, *args):
print 'foreach: args are ' + `args`
for object in object_list:
try:
object.__class__.__dict__[name_key](object, *args)
except KeyError:
pass
##########################
if __name__ == '__main__':
h=Ham()
e=Eggs()
s=Spam()
foreach ('say', [h, e, s])
foreach('speak_up', [e])
foreach('speak_up', [h, e, s], 'sandwich')
foreach('speak_up', [h, e, s], None) #can i pass None?
foreach('shout', [h, e, s], 'sandwich')
foreach('shout', [h, e, s], 'sandwich', 'beer')
--------------
This works:
foreach: args are ()
I am Ham, and I don't want any arguments, thank you.
foreach: args are ()
I am Eggs, and my arguments are bacon
foreach: args are ('sandwich',)
I am Ham, and my arguments are sandwich
I am Eggs, and my arguments are sandwich
foreach: args are (None,)
I am Ham, and my arguments are None
I am Eggs, and my arguments are None
foreach: args are ('sandwich',)
I AM SPAM AND MY ARGUMENTS ARE sandwich AND sausage
foreach: args are ('sandwich', 'beer')
I AM SPAM AND MY ARGUMENTS ARE sandwich AND beer
----------------
But is it white, grey, or black magic? Is there a better way I should have
done? Suggestions on what to name the function gratefully welcomed.
Laura Creighton
More information about the Python-list
mailing list