call list of function using list comprehension

前端 未结 4 696
无人共我
无人共我 2020-12-03 00:57

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]()         


        
相关标签:
4条回答
  • 2020-12-03 01:32

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

    0 讨论(0)
  • 2020-12-03 01:44
    >>> [f() for f in fl]
    [1, 2, 3]
    

    Absolutely :)

    0 讨论(0)
  • 2020-12-03 01:45

    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"

    0 讨论(0)
  • 2020-12-03 01:45

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

    0 讨论(0)
提交回复
热议问题