Python子函数如何调用父函数的变量

您所在的位置:网站首页 python在函数中调用函数 Python子函数如何调用父函数的变量

Python子函数如何调用父函数的变量

2023-09-17 02:30| 来源: 网络整理| 查看: 265

只读不写

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

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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3