This article mainly introduces the method of implementing counters in Python closures, analyzes the concept of closures and related techniques for implementing counters, for more information about how to implement counters using Python closures, see the example in this article. Share it with you for your reference. The specific implementation method is as follows:
Let's take a look at the professional explanation: Closure is short for Lexical Closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment.
The code is as follows:
#! /Usr/bin/ env python # coding = utf-8def generate_counter (): CNT = [0] def add_one (): CNT [0] = CNT [0] + 1 return CNT [0] return add_onecounter = generate_counter () print counter () #1 print counter () #2 print counter () #3
I hope this article will help you with Python programming.