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

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的定义(所以此时会认为x未定义);如果仅仅在fun2中对x进行读取(比如x1 = x * 2,此时会找到外层的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的定义就不会被屏蔽.

倘若x被定义在全局位置,则需要使用global.

x = 5
def
fun1(): def fun2(): global x x *= 2 return x return fun2()

参考文章:https://blog.csdn.net/zhuzuwei/article/details/78234748

猜你喜欢

转载自www.cnblogs.com/Stephen-Qin/p/10390877.html