【问题标题】:In python how can I call a function using an imported module在 python 中,如何使用导入的模块调用函数
【发布时间】:2016-10-12 17:24:09
【问题描述】:

我有这个模块调用 main() 函数:

## This is mymodules ##
    def restart():
        r = input('Do you want to build another configuration file?\n1. Yes\n2. No\n')
        if r == '1':
            main()
        elif r == '2':
            os.system('pause')

main() 位于加载此模块的另一个脚本中。但是,当它调用时,它说 main() 未定义。基本上这就是我在测试中所拥有的:

import mymodules as my
def main():
    print('good')

my.restart()

当它运行时,我希望 my.restart() 能够调用定义的 main()。

【问题讨论】:

标签: python function import module


【解决方案1】:

对于像这样简单的代码,您可以简单地将 main 函数作为参数传递给重新启动函数。

例如

def restart(function):
    r = input('Do you want to build another configuration file?\n1. Yes\n2. No\n')
    if r == '1':
        function()
    elif r == '2':
        os.system('pause')

还有:

import mymodules as my
def main():
    print('good')

my.restart(main)

这是一种流行的设计模式,称为callback

但是,这只适用于像这样的简单示例。如果您正在编写更复杂的东西,您可能想要使用对象并传递对象。这样您就可以从单个对象调用所有多个方法/函数。

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 2020-04-18
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2013-12-13
    相关资源
    最近更新 更多