invoke method on many instances
steve at REMOVE-THIS-cybersource.com.au
Fri Jul 17 09:45:08 CEST 2009
On Fri, 17 Jul 2009 05:19:50 +0000, Alan G Isaac wrote:
> As a recurrent situation, I need to invoke the same method on many
> instances. Speed matters, but the solution should be pure Python. Is
> the following convenience function a reasonable approach?
> def apply2(itr, methodname, *args, **kwargs):
> f = operator.methodcaller(methodname, *args, **kwargs)
> for item in itr:
I don't particularly like your naming conventions, but never mind.
You could also try this:
for obj in objects:
getattr(obj, methodname)(*args, **kwargs)
See also these recipes from the "Python Cookbook":
More information about the Python-list