我将以下代码放入 Jupyter Lab 的一个单元格中并运行它:
def test_algo(n):
return n+1
def test_function(x,algo=test_algo):
return algo(x)
print(test_function(1))
输出是2,那么,我把两个函数的顺序调换一下:
def test_function(x,algo=test_algo):
return algo(x)
def test_algo(n):
return n+1
print(test_function(1))
如果你把它写在.py文件中并运行它,这肯定不起作用,因为python在执行test_function时不会知道test_algo的定义。但是在 Jupyter 中它仍然有效,因为我们在更改顺序之前定义了 test_algo。有趣的是:让我们在 test_algo 中进行更改,例如将 n+1 更改为 n-1:
def test_function(x,algo=test_algo):
return algo(x)
def test_algo(n):
return n-1
print(test_function(1))
输出还是2,可能是因为没有重新定义test_algo。但令人惊讶的是,如果我们什么都不做只再次点击运行按钮:
def test_function(x,algo=test_algo):
return algo(x)
def test_algo(n):
return n-1
print(test_function(1))
输出将为 0。我们第二次运行此单元格时重新定义了函数 test_algo。
所以我的问题是,是什么导致了二审的变化? Jupyter 如何决定何时需要重新编译一个函数?
系统:Ubuntu 20.04.2 LTS
Jupyter 实验室信息: jupyter 核心:4.7.1 jupyter 笔记本:6.3.0 qtconsole : 未安装 蟒蛇:5.8.0 ipykernel:5.5.3 jupyter 客户端:6.1.12 jupyter 实验室:3.0.12 nbconvert:6.0.7 ipywidgets:未安装 nb 格式:5.1.3 特质:4.3.3