首页 > 解决方案 > 如果函数名包含特定字符串,如何在自身内部循环函数并执行其中一些函数

问题描述

我有一个脚本定义了许多功能。现在我想批量执行其中一些。

例如:

def foo_fun1():
   xxx

def foo_fun2():
   xxx

...

def bar_funx():
   yyy

如果函数名包含“foo”,我现在想循环所有函数并拾取其中一些函数,如何存档?

for fun in dir():
    if 'foo' in fun:
         #
         # the fun is string
         # how to call the string as function here??

谢谢!

标签: python

解决方案


您需要使用globals()函数,它返回dict每个全局对象的一个

def say_hey():
    print('hey')

def say_hi():
    print('hi')

def main():
    for name, func in globals().items():
        if 'say_' in name and callable(func):
            func()

if __name__ == '__main__':
    main()

哪个输出

hey
hi

https://docs.python.org/3/library/functions.html#globals


推荐阅读