Home > Backend Development > Python Tutorial > Python闭包实现计数器的方法

Python闭包实现计数器的方法

WBOY
Release: 2016-06-06 11:16:03
Original
2004 people have browsed it

本文实例讲述了Python闭包实现计数器的方法。分享给大家供大家参考。具体实现方法如下:

先来看看专业的解释:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。所以,有另一种说法认为闭包是由函数和与其相关的引用环境组合而成的实体。

代码如下:

#!/usr/bin/env python
#coding=utf-8
def generate_counter():
  CNT = [0]
  def add_one():
    CNT[0] = CNT[0] + 1
    return CNT[0]
  return add_one
counter = generate_counter()
print counter()   # 1
print counter()   # 2
print counter()   # 3
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template