0
点赞
收藏
分享

微信扫一扫

Python子函数如何调用父函数的变量 | nonlocal global 区别

点亮自己的那盏灯 2022-04-15 阅读 80
python

只读不写

子函数不修改父函数甚至函数外变量的值
如:

t = 0
def a():
    def b():
        def c():
            print(t)
        c()
    b()
a()

多级嵌套形成闭包

nonlocal

def a():
    t = 1
    def b():
        nonlocal t
        t+=10
        print(t)
    b()
a()

子函数修改祖先函数变量的值
需要注意如果如下使用会报错:

t = 1
def a():
    def b():
        nonlocal t
        t+=10
        print(t)
    b()
a()

报错:SyntaxError: no binding for nonlocal ‘t’ found
nonlocal不能绑定**祖先函数(类中也一样)**以外的变量

global

t = 0
def a():
    def b():
        global t
        t+=10
        print(t)
    b()
a()

global修饰全局变量,只能写在最外层!
函数内都不行
以下写法会报错


def a():
	t = 0
    def b():
        global t
        t+=10
        print(t)
    b()
a()
class C:
    t = 0
    def a(self):
        def b():
            global t
            t+=10
            print(t)
        b()
c = C()
c.a()

报错:NameError: name ‘t’ is not defined

同理 nonlocal不会改变最外层变量的值
global不会改变函数内变量的值

即:
在这里插入图片描述
在这里插入图片描述

t = 0
def a():
    t=100000  #这里不受影响
    def b():
        global t
        t+=10 
        print(t) #外层t
    b()
    print(t)
a()
print(t)#外层t

运行结果:
10
100000
10

t = 0
def a():
    t=100000 #只改变这里
    def b():
        nonlocal t
        t+=10
        print(t)
    b()
    print(t)
a()
print(t) #函数外的t不受影响

运行结果:
100010
100010
0

举报

相关推荐

0 条评论