Python学习笔记——利用闭包写递增函数

*前言:这篇算是一个总结笔记

利用闭包返回一个计数器函数,每次调用它返回递增整数:

  • 创建生成器:
def createCounter():
    def f():
        x = 0
        while True:
            x += 1
            yield x
    it = f()

    def number():
        return next(it)
    return number

createA = createCounter()
print(createA())
  • 列表
    def createCounter():
    	f = [0]
    	def increase():
    		f[0] = f[0] + 1
    		return f[0]
    	return increase
    
    createA = createCounter()
    print(createA())
    print(createA())
    print(createA())


你可能感兴趣的:(Python)