UnboundLocalError:在python closu中赋值之前引用的局部变量

2024-10-01 11:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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

但第二个不起作用:

^{pr2}$

执行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

它们对我来说似乎一模一样,所以我不明白为什么第二个不起作用。有什么想法吗?在


Tags: inpytestreturndeflinelinkfilename
1条回答
网友
1楼 · 发布于 2024-10-01 11:36:27

您已经用filename = os.path.join(os.getcwd(), filename)覆盖了变量,如果您将filename =更改为filename以外的内容,则不会出现local variable 'filename' referenced before assignment错误。在

一旦设置了filename =,您就不再引用传入的参数filename,而是指在定义了if之前尝试在if中使用的内部函数范围内的局部{}。在

如果将这两行和其他变量更改为类似的值,那么dest也会遇到同样的问题:

filename_ = os.path.join(os.getcwd(), filename)
dest_ = os.path.join(dest, filename)

您将看到代码运行良好,因为filename现在引用的是参数,而不是内部函数中定义的局部变量。在

如果您尝试在第一个函数中重新分配x,并在定义它之前尝试访问{},那么您将看到完全相同的行为:

^{pr2}$

如果打印__closure__属性,您将看到发生的情况:

def makeInc(x, y):
    def inc():
        return y + x
    return inc

inc5 = makeInc(5, 10)
inc10 = makeInc(10, 5)
print(inc5.__closure__)
(<cell at 0x7f180df67e50: int object at 0xef00f8>, <cell at 0x7f180df67fa0: int object at 0xef0080>)

现在重新分配x:

def makeInc(x, y):
    def inc():
        print  y + x
        x= 5
        return y + x
    return inc

inc5 = makeInc(5, 10)
inc10 = makeInc(10, 5)
print(inc5.__closure__)
(<cell at 0x7fea11889fd8: int object at 0x291e080>,)

在内部函数中重新赋值后,不再有对x的引用。在

所以基本上,两个原始函数之间的根本区别是,在一个函数中,你在局部范围内重新分配变量,而在另一个函数中则没有。从上面的代码中可以看出,如果在第一个函数中执行类似的操作,结果完全相同。在

在scopes LEGB等方面有一个很好的tuthere。。在

相关问题 更多 >