Created
March 19, 2012 16:39
-
-
Save timofurrer/2118548 to your computer and use it in GitHub Desktop.
Python functions are objects
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 shout(word="yes"): | |
return word.capitalize()+"!" | |
print shout() | |
# outputs : 'Yes!' | |
# As an object, you can assign the function to a variable like any | |
# other object | |
scream = shout | |
# Notice we don't use parenthesis: we are not calling the function, we are | |
# putting the function "shout" into the variable "scream". It means you can then | |
# call "shout" from "scream": | |
print scream() | |
# outputs : 'Yes!' | |
# More than that, it means you can remove the old name 'shout', the function will still | |
# be accessible from 'scream' | |
del shout | |
try: | |
print shout() | |
except NameError, e: | |
print e | |
#outputs: "name 'shout' is not defined" | |
print scream() | |
# outputs: 'Yes!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment