如何从导入的模块内部调用函数,也称为设计问题

恩纳

我一直在尝试寻找答案,但找不到任何东西。也许我的方法糟透了。

我有一个脚本,希望以此方式编写,以便将来可以轻松扩展(使用模块)。因此,我在上述脚本中创建了一个“注册”模块的函数。基本上,使用模块提供的键将模块提供的功能添加到字典中。

我最初的和当前的计划是从我要导入的模块中调用该函数,显然这是行不通的。我可以以某种方式从模块内部调用该函数吗?如果没有,我该如何解决?我的问题是我在这里和那里都有动态函数名称,我不能只是从给定的字符串中调用函数,所以我正在为完全相同的目的创建字典。但是,为了简单起见,我宁愿只导入所有模块,而除了在主脚本中执行任何操作以外,不执行任何其他操作。

罗伯ᵩ

如果是我,那么我的设计中将包含三个要素:

我的可扩展库:

# master.py

# List of plugins
plugins = []


# registration API called by plugin
import inspect
def register():
    frame = inspect.stack()[1]
    module = inspect.getmodule(frame[0])
    plugins.append(module)

# functional API called by application
def callout():
    for m in plugins:
        m.shout()

def dynamic_callout(s):
    for m in plugins:
        getattr(m, s[:2]+s[-3:])()

我的插件:

# plugin1.py

# Register this plugin
import master
master.register()

# Respond to request from master
def shout():
   print "Hello from", __name__

最后,我的应用程序:

# Esablish a plugin by importing it    
import plugin1

# Call the API
import master
master.callout()
master.dynamic_callout("shut up or get out")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章