我将在Python中实现两个简单的闭包。对我来说,它们看起来是一样的,但一个可以运行,而另一个则不能。
有效的代码如下:
但是第二个不起作用:
他们在我看来是完全相同的,所以我不明白为什么第二个不能运行。有任何想法吗?
有效的代码如下:
def makeInc(x, y):
def inc():
return y + x
return inc
inc5 = makeInc(5, 10)
inc10 = makeInc(10, 5)
inc5 () # returns 15
inc10() # returns 15
但是第二个不起作用:
import os
def linker(dest, filename):
print filename
def link():
if os.path.isfile(filename): # line 17
filename = os.path.join(os.getcwd(), filename)
dest = os.path.join(dest, filename)
y = rawinput('[y]/n: ln -sf %s %s' % (dest, filename))
if y == 'n':
return 1
else:
return os.system('ln -sf %s %s' %(dest, filename))
else:
return -1
return link
l = linker('~', '.vimrc')
l() # line 30
当执行l()
时,在link()
的第一行出现故障:
Traceback (most recent call last):
File "test.py", line 30, in <module>
l()
File "test.py", line 17, in link
if os.path.isfile(filename):
UnboundLocalError: local variable 'filename' referenced before assignment
他们在我看来是完全相同的,所以我不明白为什么第二个不能运行。有任何想法吗?
local filename
(注意:local 不是 Python 的实际关键字,但我只是将其与 global 进行比较)。由于 Python 使用 LEGB,它会首先找到本地变量,即使在分配之前,而不是查找封闭作用域,它会给出一个错误。 - Shashank