Automatically call all functions matching a certain pattern in python

前端 未结 4 1674
忘掉有多难
忘掉有多难 2021-01-01 03:25

In python I have many functions likes the ones below. I would like to run all the functions whose name matches setup_* without having to explicitly call them fr

4条回答
  •  情歌与酒
    2021-01-01 03:47

    You can use locals()

    L = locals()
    for k in L:
        if hasattr(L[k], '__call__') and k.startswith('setup'):
            L[k]()
    

    Of course you'll want to make sure that your function names don't appear elsewhere in locals.

    In addition, you could also do something like this because functions are first class objects (note the function names are not strings):

    setupfunctions = [setup_1, setup_2, setup_3, myotherfunciton]
    for f in setupfunctions:
        f()
    

提交回复
热议问题