Discuss / Python / day8.总结与理解

day8.总结与理解

Topic source

haildceu1

#12 Created at ... [Delete] [Delete and Lock User]

每次引用createCounter()的时候, "L=[0]   #初始化列表L为0"  这句话不会重置L吗,为什么后面使用的是加1后的L呢?

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

首先你要先理解一个概念:如果在函数内部任何位置为变量赋值,除非明确声明为,否则均将其视为该函数的局部变量

方法一,如果不加nonlocal关键字,变量x 就是counter函数的局部变量,那 x = x + 1 就会抛出异常

UnboundLocalError: local variable 'x' referenced before assignment

至于加 nonlocal 关键字,楼主已经解释了,就是用于嵌套函数中,声明该变量非counter函数的局部变量,而是在往外层作用域中寻找该变量,逐级向外查找,直到嵌套作用域内中都查找不到,代码抛出异常为止!

方法二,我觉得楼主解释的不对, L[0]+=1  这一步看似是L赋值,实则是修改 L 这个对象中的一个元素值,它仍是引用了外层createCounter函数的局部变量,而不是counter函数的局部变量,所以它不需要 nonlocal 关键字声明

def createCounter():
    L=[0]  
    def counter():
        
        nonlocal L      # 显式声明非局部变量
        L = [L[0]+1]    # UnboundLocalError: local variable 'x' referenced before assignment
        return L[0]
    return counter

counter = createCounter()
print(counter(), counter(), counter())

上面这种情况,仍旧是需要 nonlocal 关键字声明,不然也会抛出异常

大白话就是:如果在函数内给变量赋值,那就是生成了一个函数的局部变量;但是,如果你是想要引用外部变量,修改外部变量的值,那就要使用关键字(nonlocal、global)声明变量

                     如果在函数内没有变量赋值的行为,那就是引用了外部变量


  • 1
  • 2

Reply