The pythonic way of calling a class function if I have a list of instances

So, I have a list containing several instances of the class.

As I move forward, I would like to call the method runfor the class at every step .

So far I have what is below. But is there a better or more Pythonic way to achieve the block for c in objs:?

Thank!

#!/usr/bin/python

class the_class:
    def __init__(self):
        self.num=1
    def run(self):
        self.num+=1

def main():
    objs=[]
    objs.append(the_class())
    objs.append(the_class())
    objs.append(the_class())

    for t in range(10):
        for c in objs:
            c.run()

    print objs[0].num

main()
+3
source share
4 answers

No, what you have is quite reasonable and pythonic.

List comprehension syntax:

[c.run() for c in objs]

Saves you one line, but using lists for side effects is usually considered bad.

+10
source

No, you are fine.

. .

. , .

( , comp map ), , . , , .

+6

map, , :

map(lambda x:x.run(),objs) 

, "". , , , , , , , map. , , , multiprocessing Pool, , map (http://docs.python.org/library/multiprocessing.html). , , .

EDIT

, ( lambda) . , ( ), map multiprocessing.Pool.map .

+1

python 3 , .

def exhaust(gen):
    for _ in gen: pass

# Using map
exhaust(map(lambda x: x.run(), c))

# Using generator comprehension (better)
exhaust(x.run() for x in c)

*:

def nop(*args): pass
nop(*(x.run() for x in c))

, . , , .

EDIT: , wim.

0

All Articles