python函数常见关键字分享
目录
1.global关键字2.nolocal关键字3.yield from1.global关键字
默认情况下,在局部作用域对全局变量只能进行:读取,修改内部元素(可变类型),无法对全局变量进行重新赋值
读取:
CITY=["北京","上海"] def func(): print(CITY) # ["北京","上海"] func()
修改内部元素(可变类型)
CITY=["北京","上海"] def func(): CITY.append("安徽") print(CITY) # ["北京","上海","安徽"] func() print(CITY) # ["北京","上海","安徽"]
无法对全局变量重新赋值
CITY=["北京","上海"] def func(): CITY=["安徽"] print(CITY) #["安徽"] func() print(CITY) # ["北京","上海"]
如果想在局部作用域对全局变量重新赋值,基于global关键字实现
CITY=["北京","上海"] def func(): global CITY=["安徽"] print(CITY) #["安徽"] func() print(CITY) #["安徽"]
2.nolocal关键字
将上一级作用域的变量重新赋值
name = "root" def outer(): # name=123 name = "你好" def func(): # 将又上一级变量name重新赋值为123 nonlocal name # name=123 name = "wxy" def inner(): #将上一级变量name重新赋值为123 nonlocal name name = 123 inner() print(name) func() print(name) outer() print(name) # 123 # 123 # root
3.yield from
python3.3引入yield from
在yield函数中调用其它的yield函数
def func(): yield 2 yield 2 def func1(): yield 1 yield 1 yield from func() yield 1 from i in func1(): print(1)
到此这篇关于python函数常见关键字分享的文章就介绍到这了,更多相关python函数关键字内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
X 关闭
X 关闭