自动调用python中匹配某个模式的所有函数 [英] Automatically call all functions matching a certain pattern in python

查看:15
本文介绍了自动调用python中匹配某个模式的所有函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中,我有很多函数,如下所示.我想运行名称与 setup_* 匹配的所有函数,而不必从 main 显式调用它们.函数运行的顺序并不重要.我怎样才能在 python 中做到这一点?

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 from main. The order in which the functions are run is not important. How can I do this in python?

def setup_1():
    ....

def setup_2():
    ....

def setup_3():
    ...

...

if __name__ == '__main__':
    setup_*()

推荐答案

def setup_1():
    print('1')

def setup_2():
    print('2')

def setup_3():
    print('3')

if __name__ == '__main__':    
    for func in (val for key,val in vars().items()
                 if key.startswith('setup_')):
        func()

收益

# 1
# 3
# 2

这篇关于自动调用python中匹配某个模式的所有函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆