常见的local variable 'x' referenced before assignment问题

来源:互联网 发布:mac os系统在哪下载 编辑:程序博客网 时间:2024/05/21 10:10
def fun1():    x = 5    def fun2():        x *= 2        return x    return fun2()

如上代码,调用fun1()

运行会出错:UnboundLocalError: local variable 'x' referenced before assignment。

这是因为对于fun1函数,x是局部变量,对于fun2函数,x是非全局的外部变量。当在fun2中对x进行修改时,会将x视为fun2的局部变量,屏蔽掉fun1中对x的定义;如果仅仅在fun2中对x进行读取,则不会出现这个错误。

解决办法:使用nonlocal关键字

def fun1():    x = 5    def fun2():        nonlocal x        x *= 2        return x    return fun2()fun1()Out[14]: 10

使用了nonlocal x后,在fun2()中就不再将x视为fun2的内部变量,fun1函数中对x的定义就不会被屏蔽掉。

阅读全文
0 0
原创粉丝点击