zoukankan      html  css  js  c++  java
  • python函数嵌套出现报错UnboundLocalError原理的猜测(有解决办法,但是对于报错原理不确定)

    问题的前提:在函数A内部建立函数B,B中对A中声明变量的操作。
    def A():
    x, res = 1, []
    def B():
    x = 4
    print('B:', x) # 显示 4
    B()
    print('A:', x) # 显示 1
    A()
    如果在函数B内有对A中创建的变量名进行修改,修改的意思是对该名字进行赋值,解释器会认为是一个局部变量,不会报错
    实测另一段代码:
    def A():
    x, res = 1, []
    def B():
    if x != 2:  # 区别
    x = 4
    print('B:', x)
    B()
    print('A:', x)
    A()
    会报错UnboundLocalError: local variable xx referenced before
    assignment(译:局部变量xx在被分配赋值之前是被引用或是占用的)
    猜测:py是标签语言。在B中赋值x=4,解释器认为x是B的一个局部变量,但在if中它x应该是指A中的x(因为此前B没声明过该变量)二者解释是冲突的。

    类似对值变量x,如果是对res做修改,如下:
    def A():
    global x
    x, res = 1, []
    def B():
    global x
    if x != 2:
    x = 4
    res = res[:]
    print('B:', x, res)
    B()
    print('A:', x, res)
    A()
    居然也会报错UnboundLocalError: local variable 'res' referenced before assignment
    同理x。如果是在B内写res = [3],就是局部变量,如果在B内写res.append(4),就是对A的res操作的,两个输出都是res = [4]

    如果想用B操控A的变量,实际中遇到的情况是我想在B中递归B,来操控A中一个值。需要在两个函数中都声明global x(丑死)
    def A():
    global x
    x, res = 1, []
    def B():
    global x
    if x != 2:
    x = 4
    print('B:', x) # x = 4
    B()
    print('A:', x) # x = 4
    A()
    只在A中声明:UnboundLocalError: local variable 'x' referenced before assignment
    只在B中声明:NameError: name 'x' is not defined
    如果是A的形参,在子函数B中也不可以直接赋值,原理同上面,就是python赋值的特性是改标签,会使得之前的标签指代的值无法被显示。处理方法不能是同上的
    global声明,如果对形参global会报错SyntaxError: name 'x' is parameter and global。就只能传形参给子函数。
  • 相关阅读:
    init-method,@postcontruct,afterPropertiesSet的先后顺序
    读写分离与分库分表,分布式事务面试题
    innerHTML的HTML居然必须大写..不可思议
    postgres/greenplum unnest(Array) 实现列转行
    AWS EBS磁盘挂载和卸载
    当npm 与淘宝镜像cnpm运行都很慢时候
    IntersectionObserver API 之学习
    vue之队列过渡组效果,后进先出坑点
    ele之vue3.0的form表单验证与重置
    vue3.0之DOM的$refs之运用
  • 原文地址:https://www.cnblogs.com/s1mplelectronic/p/14323074.html
Copyright © 2011-2022 走看看