Discuss / Python / 不懂为什么能循环的输出1 2 3 4 5

不懂为什么能循环的输出1 2 3 4 5

Topic source

zyckhuntoria

#1 Created at ... [Delete] [Delete and Lock User]

def createCounter(): n=0 def counter(): nonlocal n n=n+1 return n return counter

为什么通过: 1、调用counterA = createCounter() 2、输出print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 就可以得出1 2 3 4 5 每次调用保留了n的值吗? 菜鸟一枚,还请大家解惑

我理解的是: counterA 等于返回函数counter

counter这个函数被调用一次,就执行一次+1,再调用再+1,所以最后就能输出1 2 3 4 5 了。

个人理解,如果不对。。欢迎大神来纠正我的理解。。。

MRHuSt

#3 Created at ... [Delete] [Delete and Lock User]

我理解的是:应该是关键字nonlocal的缘故!因为在这里使用nonlocal关键字的目的就是使得内部函数counter()中的变量‘n’和外部函数createCounter()中的变量‘n’为同一定义,所以当内部函数中的n发生变化,外部函数中的n应该也会跟着变化。所以在下一次调用外部函数createCounter()时,n是上一次的结果!(个人理解!!!)

https://blog.csdn.net/luosongqing/article/details/75052763

这个链接对nonlocal 关键字做了很好的解释

就可以回答楼主的问题了。


  • 1

Reply