【问题标题】:How to call functions from variable names如何从变量名中调用函数
【发布时间】:2021-10-25 04:16:36
【问题描述】:

我的文件结构如下:

main.py
commands
  | __init.py__
  | a.py
  | b.py

在我的__init__.py 中,我有以下代码可以从命令文件夹中动态导入所有内容:

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

main.py 中有from commands import *

a.pyb.py 里面我有以下内容:

def foo():
  return "bar"

我希望能够从变量中调用ab 中的foo(),有点像x = commands.{input()}.foo(),但我不知道该怎么做。

【问题讨论】:

    标签: python function call


    【解决方案1】:

    这将起作用:

    from commands.a import foo as foo_a
    from commands.b import foo as foo_b
    
    foo_a()
    
    foo_b()
    

    【讨论】:

    • 除了我需要能够从变量中调用foo_a(),如果我可以动态导入函数,我更喜欢,所以我每次添加时都不必添加更多导入命令文件夹中的新功能
    • 对于 foo 被称为类似 my_variable.foo() 的它必须分配为 my_variable 是一个实例的类的方法。
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2011-03-23
    相关资源
    最近更新 更多