Created
March 19, 2012 16:41
-
-
Save timofurrer/2118622 to your computer and use it in GitHub Desktop.
Python function returns 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
def getTalk(type="shout"): | |
# We define functions on the fly | |
def shout(word="yes"): | |
return word.capitalize()+"!" | |
def whisper(word="yes") : | |
return word.lower()+"..."; | |
# Then we return one of them | |
if type == "shout": | |
# We don't use "()", we are not calling the function, | |
# we are returning the function object | |
return shout | |
else: | |
return whisper | |
# How do you use this strange beast? | |
# Get the function and assign it to a variable | |
talk = getTalk() | |
# You can see that "talk" is here a function object: | |
print talk | |
#outputs : <function shout at 0xb7ea817c> | |
# The object is the one returned by the function: | |
print talk() | |
# And you can even use it directly if you feel wild: | |
print getTalk("whisper")() | |
#outputs : yes... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment