0

考虑以下代码:

aDict = {}    
execfile('file.py',globals(),aDict)
aDict['func2']() # this calls func2 which in turn calls func1. But it fails

file.py包含以下内容

def func1():
    return 1

myVar = func1() # checking that func1 exists in the scope

func2 = lambda: func1()

这给出了一条错误消息“ NameError: global name 'func1' is not defined。”

我不确定这里发生了什么。file.py
中 的代码使用空的本地命名空间执行。 然后,在该代码中,定义了一个新函数,该函数立即被成功调用。这意味着该功能确实存在于该范围内。

那么...为什么func1不能在 lambda 中调用?

在其他语言中,lambdas/closures 绑定到定义它们的范围。
Python中的规则是怎样的?它们是否绑定到范围?到命名空间?

4

1 回答 1

0

我认为func1中定义的命名空间(file.py的命名空间)已经没有了,所以它无法再次查找它。这是记住 func1 的代码,尽管它很难看:

func2 = (lambda x: lambda : x())(func1)
于 2014-11-14T23:25:39.257 回答