在python中,如何使用导入的模块调用函数

在python中,如何使用导入的模块调用函数,python,function,import,module,Python,Function,Import,Module,我有一个调用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()函数的模块:

## 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()。

对于像这样简单的代码,只需将
main
函数作为参数传递给restart函数即可

例如

以及:

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


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

对于像这样简单的代码,您只需将
main
函数作为参数传递给restart函数即可

例如

以及:

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

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

main()
不在第一个模块的名称空间中。您可以导入它,但通常。
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)