Created
April 29, 2013 06:29
-
-
Save sidchilling/5480003 to your computer and use it in GitHub Desktop.
Script to show how functions in python 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
| # Script to show how functions are just objects | |
| def shout(word = 'yes'): | |
| return '%s!' %(word.capitalize()) | |
| print shout() # Outputs: Yes! | |
| scream = shout | |
| # As functions are just objects, we can assign them just like a variable assignment | |
| print scream() | |
| # We can then call the function using the variable which we just made an assignment to | |
| del shout | |
| # Deleting the symbol "shout" which was the name of the function initially | |
| try: | |
| print shout() | |
| except NameError as e: | |
| print 'exception: %s' %(e) | |
| # We attempt to call "shout" which we just deleted and we get a NameError as the symbol | |
| # does not exist | |
| print scream() | |
| # Outputs: Yes! | |
| # However the function still exist because just like an object there is a symbol pointing to | |
| # the function. So we can call the function using the "scream" symbol |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment