def closure_add():
x = 3
def adder():
nonlocal x
x+=1
return x
return adder
a = closure_add()
b = closure_add()
print(a())
print(b())
print(b())
print(b())
The output is:
4
4
5
6
If variable 'b' which holds the function 'adder' remembers the scope of variable (x=3), shouldn't the output be '4' no matter how many times you call it.
Links below should provide more info:
What this boils down to in the end in your example:
a and ba once, it increases the value onceb three times which increases the value three timesSince the value that gets increased in the closure is defined in the method that increases it as nonlocal, the value is stored after each change that is done to it in the parent function, in the x variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With