闭包--求助帖

**

为什么下面两种闭包调用结果不一样?

**
第一种

def funX():
    x=5
    def funY():
        nonlocal x
        x+=1
        return x
    return funY()

a=funX()
print(a)
print(a)
print(a)

结果

D:\recent\code\venv\Scripts\python.exe D:/recent/code/venv/test.py
6
6
6

进程已结束,退出代码0

第二种

def funX():
    x=5
    def funY():
        nonlocal x
        x+=1
        return x
    return funY

a=funX()
print(a())
print(a())
print(a())

结果

D:\recent\code\venv\Scripts\python.exe D:/recent/code/venv/test.py
6
7
8

进程已结束,退出代码0

为啥print的结果不一样???

发布了19 篇原创文章 · 获赞 7 · 访问量 883

猜你喜欢

转载自blog.csdn.net/Pyouthon/article/details/104742269