Automatically call all functions matching a certain pattern in python

前端 未结 4 1668
忘掉有多难
忘掉有多难 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 04:07

    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
    

提交回复
热议问题