Last active
August 29, 2015 14:07
-
-
Save tmeissner/e96e111735236bf6c4d3 to your computer and use it in GitHub Desktop.
Some experiments with closures in Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def closure(): | |
container = 0 | |
def inc(): | |
nonlocal container | |
container += 1 | |
def get(): | |
return container | |
def dec(): | |
nonlocal container | |
container -= 1 | |
def set(item): | |
nonlocal container | |
container = item | |
return inc, dec, set, get | |
if __name__ == "__main__": | |
inc, dec, set, get = closure() | |
set(1) | |
for i in range(10): | |
inc() | |
for i in range(5): | |
dec() | |
print(get()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment