Created
April 29, 2013 06:35
-
-
Save sidchilling/5480019 to your computer and use it in GitHub Desktop.
Script to show how to return a function from another function
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
| # Script to show how functions can return functions | |
| def get_talk(type = 'shout'): | |
| # We define some functions here on the fly. | |
| def shout(word = 'yes'): | |
| return '%s!' %(word.capitalize()) | |
| def whisper(word = 'yes'): | |
| return '%s...' %(word.lower()) | |
| # Then we return one of these functions | |
| if type == 'shout': | |
| # Note that while returning a function we are not using (). That will call the | |
| # function instead of returning the function. | |
| return shout | |
| else: | |
| return whisper | |
| # How to use this? | |
| talk = get_talk() | |
| # Call the get_talk() and assign the returned function to a variable "talk". | |
| print talk | |
| # Outputs: <function shout at 0xb75ee534> | |
| # Now we can call the returned function | |
| print talk() | |
| # Outputs: Yes! | |
| # We can also combine the assignment of the returned function and calling it in one go! | |
| print get_talk(type = 'whisper')() | |
| # Outputs: yes... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment