自动调用匹配蟒蛇特定模式的所有功能 [英] Automatically call all functions matching a certain pattern in python

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

问题描述

在Python中我有很多喜欢的功能在下面的人。我想运行其名称符合所有的功能设置_ * ,而不必从主显式调用它们。在该功能的执行顺序并不重要。我怎样才能做到这一点在Python?

  DEF setup_1():
    ....高清setup_2():
    ....高清setup_3():
    ......如果__name__ =='__main__':
    建立_*()


解决方案

  DEF setup_1():
    打印(1)高清setup_2():
    打印('2')高清setup_3():
    打印('3')如果__name__ =='__main__':
    在(在瓦尔()VAL关键,VAL FUNC。项目()
                 如果key.startswith('setup_')):
        FUNC()

收益

 #1
#3
#2

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

yields

# 1
# 3
# 2

这篇关于自动调用匹配蟒蛇特定模式的所有功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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