call list of function using list comprehension

2019-01-22 12:28发布

can I call a list of functions and use list comprehension?

def func1():return 1
def func2():return 2
def func3():return 3

fl = [func1,func2,func3]

fl[0]()
fl[1]()
fl[2]()

I know I can do

for f in fl:
   f()

but can I do below ?

[f() for f in fl]

A additional question for those kind people, if my list of functions is in class, for example

class F:

    def __init__(self):
        self.a, self.b, self.c = 0,0,0

    def func1(self):
        self.a += 1

    def func2(self):
        self.b += 1

    def func3(self):
        self.c += 1

    fl = [func1,func2,func3]

fobj= F()

for f in fobj.fl:
    f()

does it work?

4条回答
ゆ 、 Hurt°
2楼-- · 2019-01-22 12:39
>>> [f() for f in fl]
[1, 2, 3]

Absolutely :)

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-22 12:39

Yes, you can - the functions get called as intended.

查看更多
趁早两清
4楼-- · 2019-01-22 12:40

Of course you can as Fábio Diniz said :), However for the class method when used as a callable, an object must be given as an argument:

fobj= F()

for f in fobj.fl:
    f(fobj)

The object must be given as an argument to the callable because when you look at the definition of the method def funcX(self): the method needs one argument "self"

查看更多
乱世女痞
5楼-- · 2019-01-22 12:57

Yes, you can. The resultant list will hold the return values of your functions.

查看更多
登录 后发表回答