无法从导入的函数中调用函数

随机鲍勃

我有 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: name 'function_1' is not defined'。我认为当您导入一个函数时,它会被添加到导入模块的命名空间中。如果是这样,为什么 strategy() 看不到 function_1()?

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

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

切普纳

Python 是静态范围的。查找为一个自由变量(例如function_1)进入虽然其中范围strategy限定,而不是其中它被称为。正如strategy在模块的全局范围中定义的那样Strategy_File,这意味着寻找Strategy_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)

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章