invoke method on many instances

Rainer Grimm r.grimm at science-computing.de
Sun Jul 19 13:08:00 CEST 2009


Hallo Alan,
> def apply2(itr, methodname, *args, **kwargs):
>     f = operator.methodcaller(methodname, *args, **kwargs)
>     for item in itr:
>         f(item)
you can do it in a functional way.

>>> class A(object):
...   def hello(self): return "hello: " + str
( self.__class__.__name__ )
...
>>> class B(A):pass
...
>>> class C(A):pass
...
>>> a=A()
>>> b=B()
>>> c=C()
>>> a.hello()
'hello: A'
>>> b.hello()
'hello: B'
>>> c.hello()
'hello: C'
>>>
>>> map( (lambda obj : getattr(obj,"hello")()),(a,b,c))
['hello: A', 'hello: B', 'hello: C']
>>> [ getattr(obj,"hello")() for obj in (a,b,c)]
['hello: A', 'hello: B', 'hello: C']

Greetings from Rottenburg,
Rainer



More information about the Python-list mailing list