The example in this paper describes how Python closures implement counters. Share to everyone for your reference. The implementation method is as follows:
Let's take a look at the professional explanation: Closures (Closure) are short for lexical closures (Lexical Closure) and are functions that reference free variables. This quoted free variable will exist with this function, even if it has left the environment in which it was created. So, there is another argument that closures are entities that are composed of functions and their associated 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 () # 1print counter () # 2print counter () # 3
Hopefully this article will help you with Python programming.