python函数关键字
荼靡, 人气:01.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)
加载全部内容