首页 > 解决方案 > 无法从导入的函数中调用函数

问题描述

我有 2 个文件,第一个名为 function_call_test.py 并包含以下代码;

from Strategy_File import strategy

def function_1():
    print('This works')

strategy()

第二个文件名为 Strategy_File.py,包含以下代码;

def strategy():
    print('got here')
    function_1()

运行第一个脚本时,我得到'NameError:名称'function_1'未定义'。我认为当您导入一个函数时,它会被添加到导入模块命名空间中。如果是这样,为什么 strategy() 看不到 function_1()?

同样重要的是,我该如何完成这项工作。以上仅用于演示目的,我有理由希望 strategy() 位于单独的模块中。

Python 3.6、Windows 7-64、Visual Studio 2019 和 IDLE

标签: pythonpython-import

解决方案


Python 是静态作用域的。对自由变量(例如 )的查找通过定义function_1的范围而strategy不是调用它的范围进行。正如在模块的全局范围内定义的那样,这意味着寻找,并且未定义该功能。strategyStrategy_FileStrategy_File.function_1

如果要strategy当前全局范围内调用某些东西,则需要将其定义为接受可调用参数,并在调用时传递所需的函数strategy

# Strategy_File.py

# f is not a free variable here; it's a local variable
# initialized when strategy is called.
def strategy(f):
    print('got here')
    f()

# function_call_test.py

from Strategy_File import strategy


def function_1():
    print('This works')

# Assign f = function_1 in the body of strategy
strategy(function_1)

推荐阅读