global/nonlocal强制修改全局变量
子作用域中只能 找到父级中的值 ,默认无法重新为父级的变量进行赋值。(global/nonlocal可以强制做)
# #####################
name = 'oldboy'
def func():
name = 'alex' # 在自己作用域再创建一个这样的值。
print(name)
func()
print(name)
# #####################
name = [1,2,43]
def func():
name.append(999)
print(name)
func()
print(name)
# ###################### 如果非要对全局的变量进行赋值
# 示例一
name = ["老男孩",'alex']
def func():
global name
name = '我'
func()
print(name)
# 示例一
name = "老男孩"
def func():
name = 'alex'
def inner():
global name
name = 999
inner()
print(name)
func()
print(name)
name = "老男孩"
def func():
name = 'alex'
def inner():
global name
name = 999
inner()
print(name)
func()
print(name)
# ############################## nonlocal
name = "老男孩"
def func():
name = 'alex'
def inner():
nonlocal name # 找到上一级的name
name = 999
inner()
print(name)
func()
print(name)
标签:11,name,global,nonlocal,函数参数,func,print,def
From: https://www.cnblogs.com/jhchena/p/18432427