python - 无法从导入的函数中调用函数
问题描述
我有 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
解决方案
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)
推荐阅读
- javascript - 如何在服务可用的所有模块(页面)中都可用的服务中实现 Ionic 模式?
- python - 在 XML 文件中查找子项的更好方法是什么?
- python - Python 社交身份验证“AuthForbidden”
- selenium - JMeter 的 WebDriver 的 Javascript 解释器无法访问第二个选项卡窗口
- python - 创建一条穿过一个点并围绕该点旋转直到它碰到另一个点的线,这会导致它围绕新点旋转
- xamarin - Xamarin Forms Timepicker 格式输入字符串格式不正确
- c# - 使用 AseDataAdapter.Fill() 方法的 sybase 列是否有最大字符限制?
- apache-spark - Apache Spark:用分号替换特定列中的每个点
- javascript - Typescript 项目 - 如何将导入的模块合并到最终构建中?
- javascript - 使用 ews-javascript-api 更新交流会议时出错