开发者

Calling a class functions using map

开发者 https://www.devze.com 2023-03-18 21:15 出处:网络
Sorry if this has been asked but I couldn\'t find anything online to indicate if this was possible. The easiest way I can explain this is just with a code segment, with this just being representative

Sorry if this has been asked but I couldn't find anything online to indicate if this was possible. The easiest way I can explain this is just with a code segment, with this just being representative of my problem:

class A:
    def a(self,):
        print "Hello"
B =开发者_如何转开发 [A for i in xrange(10)]
map(self.a,B)

Basically I wanted to iterate over the array of self defined classes and call the class function. For reference in case it matters the function of the class is self contained and doesn't return anything, it causes a change in internal variables. Any help is really appreciated and at the end of the day I want to use it with multiprocessing.Pool.

Thanks, Ali


Is this what you want?

>>> class A:
...  def a(self):
...   print "Hello"
... 
>>> B = [A() for i in xrange(10)]
>>> map(lambda a: a.a(), B)
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
[None, None, None, None, None, None, None, None, None, None]


You almost never want to use map in Python; it's almost entirely obsoleted by list comprehensions.

class A(object):
    def a(self):
        print "Hello"

B = [A() for i in xrange(10)]
[obj.a() for obj in B]


map() and list comprehensions will both generate a list of the results of calling the method of each object. They're the way to go if that's a non-issue because they're both short and sweet.

Here's a different approach that is longer to setup but avoids the results list creation and can also handle passing one or more arguments on each call. It's somewhat similar to a multiprocessing.Pool object's apply() method.

class A(object):
    def a(self):
        print "Hello"
    def b(self, name):
        print "Hello", name

def apply_method(method, seq, *args):
    if args:
        generator = (getattr(obj, method)(*args) for obj in seq)
    else:
        generator = (getattr(obj, method)() for obj in seq)
    try:
        while True:
            generator.next()
    except StopIteration:
        pass

B = [A() for i in xrange(10)]

apply_method('a', B)
apply_method('b', B, 'Guido')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号