|
|
发表于 2020-10-16 23:03:42
|
显示全部楼层
def funX():
x = 5
def funY():
nonlocal x
x += 1
return x
return funY
a = funX() #本行代码执行后,a = funy,是一个函数对象,没有括号说明a的赋值不是funy函数对象的返回值
print(a()) #本行代码执行的是print(funy()),也就是打印funy() 的返回值,此时X初始值为非局部变量,因此x初始值为5,运算后为6,
# funy() 的返回值为6,打印6。后7、8同
print(a())
print(a())
======================可以加代码验证分析结果是否正确==================
def funX():
x = 5
def funY():
nonlocal x
x += 1
return x
return funY
a = funX()
print(type(a))
print(type(funX()))
=========运行结果==========
<class 'function'> #a的打印结果
<class 'function'> #funX()函数返回值的打印结果
>>> a
<function funX.<locals>.funY at 0x031970B8> #这里已经很能说明问题了
>>> |
|