zoukankan      html  css  js  c++  java
  • 常见的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未定义,C++中则不会这样);如果仅仅在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

    新战场:https://blog.csdn.net/Stephen___Qin
  • 相关阅读:
    firefox浏览器播放音频
    Font Awesome图标字体应用及相关
    PHP输出A到Z及相关
    TensorFlow安装填坑之路(Windows环境)
    Git常用命令(一)
    spring boot 入门(一)
    JHipster简介
    Spring Boot实现文件下载功能
    IntelliJ IDEA插件系列
    什么是RESTful API?
  • 原文地址:https://www.cnblogs.com/Stephen-Qin/p/10390877.html
Copyright © 2011-2022 走看看