In this example, printer is a closure as it points to a code block with a free variable of "msg". The variable msg is closed over the printer() function.
def make_printer(msg):
def printer():
print msg
return printer
printer = make_printer('Foo!')
printer()
This printer method is not a closure but nested function, as in this case "msg" variable is nothing but a local variable that is not "closed".
def make_printer(msg):
def printer(msg=msg):
print msg
return printer
printer = make_printer("Foo!")
printer() # "Foo!"
printer("Hello") # --> "Hello"
No comments:
Post a Comment