python - 如果函数名包含特定字符串,如何在自身内部循环函数并执行其中一些函数
问题描述
我有一个脚本定义了许多功能。现在我想批量执行其中一些。
例如:
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??
谢谢!
解决方案
您需要使用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
推荐阅读
- php - 使用 Eloquent 在两个不同的表和两个不同的列中进行查询
- php - Symfony 中 PHP 和 Twig 的区别?
- google-cloud-platform - Google BigQuery P4 服务帐号需要 iam.serviceAccounts.getAccessToken 错误
- elasticsearch - 以任何顺序匹配所有单词,但重复的单词被视为单个单词
- python - L1 vs L2或MSE vs MAE和欧几里得范数..公式不同?为什么可以互换使用?
- flutter - 需要像 Flutter 中的 Uber 一样的 Voip 通话
- javascript - 如何使用 Node JS 在计算机上检测 Web 调试器?
- bash - 如何从用户用户以 root 身份运行 bash 脚本?
- ios - IOS 错误:由于 ionic3 中未捕获的异常“NSUnknownKeyException”而终止应用程序?
- r - ifelse 和 fromJSON 在管道中的奇怪行为