# global
# 1、在局部作用域声明(创建)一个全局变量
name = 'hello'
def func1():
name = 'ait'
print(name) # ait
func1()
print(name) # hello
def func1():
global name1
name1 = 'ait'
print(name1) # ait
func1()
print(name1) # ait
# 2、修改全局变量
count = 1
def func3():
global count
count += 1
return count
print(func3()) # 2
# nonlocal
# 1、不能操作全局变量
"""
count = 1
def func3():
nonlocal count
count += 1
return count
print(func3()) # 报错
"""
# 2、局部作用域:内层函数对外层函数的局部变量进行修改。
"""
def wrapper():
count = 1
def inner():
count += 1 # 报错,局部只能引用全局变量,不能修改;小范围只能引用大范围的,不能修改
inner()
wrapper()
"""
def wrapper():
count = 1
def inner():
nonlocal count
count += 5
inner()
return count
print(wrapper()) # 6
python关键字global和nonlocal
最新推荐文章于 2024-09-03 17:22:28 发布