invoke method on many instances

Piet van Oostrum piet at cs.uu.nl
Sun Jul 19 09:24:26 EDT 2009


>>>>> Rainer Grimm <r.grimm at science-computing.de> (RG) a écrit:

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

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

But that creates an unnecessary list.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list