简体   繁体   中英

Calling functions one by one from a python list

I have a list of functions say

list1 = ['foo','boo','koo']

now I want to call these functions one by one.

for i in range(len(list1)):
    list1[i](<argumentslist>)

This gives me an error:

TypeError: 'str' object is not callable

How Should I make this possible ?

在列表中删除'

list1 = [foo,boo,koo]

Your list is does not contain a function objects, you are storing a string. Functions are first class object in python. If you want to store it as a list and call them use the function object as follows. list = [foo, bar ] list[0](args)

Currently the elements in your list are strings. Given that you have defined functions foo , boo , koo you can put these in a list without the ' surrounding them. Ie you will be making a list of functions, not a list of string function names.

Not recommended but:

def hello_world(int_):
    print("hello{}".format(int_))

list_ = ["hello_world"]
arg = 2

for i in list_:
    exec("{}({})".format(i,arg))

#hello2

You do not have to remove the quotes if you use **kwargs :

def the_function(**functions): 

    list1 = ['foo','boo','koo']
    for i in range(len(list1)):
        val = functions[list1[i]](3)

f1 = lambda x: pow(x, 2)
f2 = lambda x: x+3
f3 = lambda x: sum(i for i in range(x))

the_function(foo = f1, boo = f2, koo = f3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM