How to implement counters using Python closures

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.