python counter with closure

后端 未结 2 409
醉梦人生
醉梦人生 2021-01-06 13:58

I\'m trying to build a counter in python with the property of closure. The code in the following works:

def generate_counter():
    CNT = [0]
    def add_one         


        
2条回答
  •  被撕碎了的回忆
    2021-01-06 14:29

    It doesn't have to be a list, it just has to be an mutable object which you mutate, not reassign.

    From the docs:

    If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

    Thus, in your second example, x is considered local (to the inner function), and, after your first assignment, you're shadowing the outer 'x'.

    On the other hand, in the first example (since you don't assign a value to CNT) it operates on the CNT defined in the outer function.

提交回复
热议问题