CSC/ECE 517 Spring 2014/ch1 1w1l m: Difference between revisions
Jump to navigation
Jump to search
(Somewhat better closure example) |
(→What is a closure?: Tried to shorten closure example) |
||
Line 9: | Line 9: | ||
#!/usr/bin/env python | #!/usr/bin/env python | ||
def closure_builder(message="Default"): | def closure_builder(message="Default"): | ||
def closure(): | def closure(): | ||
Line 19: | Line 18: | ||
default_closure = closure_builder() | default_closure = closure_builder() | ||
custom_closure = closure_builder("Custom") | custom_closure = closure_builder("Custom") | ||
# Call the closures you built | # Call the closures you built |
Revision as of 07:12, 23 February 2014
Design Patterns Involving Closures
Background
What is a closure?
Very simply, a closure is a function that can use a variable that was valid within the scope that the closure was defined, but need not be in-scope where the closure is called. A quick example is very illustrative.
#!/usr/bin/env python
def closure_builder(message="Default"):
def closure():
# Message is in-scope here
print message
return closure
# Build two functions
default_closure = closure_builder()
custom_closure = closure_builder("Custom")
# Call the closures you built
default_closure() # Amazingly, prints "Default"
custom_closure() # Amazingly, prints "Custom"
Examples
Narration
Links to Important Terms
References
<references />