Last active
December 22, 2015 03:29
-
-
Save soedar/6410980 to your computer and use it in GitHub Desktop.
CS1010S Tutorial 2 HOF Example
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 bank_account(balance): | |
| # Inner functions are created in the scope of the | |
| # outer function, and as such have 'knowledge' of | |
| # the scope. | |
| # | |
| # In this case, it knows about the balance. | |
| # This function returns a string telling us | |
| # whether the owner is rich or poor | |
| def are_you_rich(): | |
| # The inner function can access/read the variables | |
| # defined in the outer scope, but it *cannot* | |
| # modify it (Sorry!) | |
| if balance > 1000: | |
| return "rich!" | |
| else: | |
| return "poor :(" | |
| # Returns the are_you_rich *function* | |
| # that has bounded to the current scope | |
| return are_you_rich | |
| ###### | |
| # Test | |
| ###### | |
| my_account = bank_account(50) | |
| your_account = bank_account(5000) | |
| # Now my_account and your_account are *functions*, | |
| # so you have to invoke them to get the output | |
| print("I am", my_account()) # Out: I am poor ;( | |
| print("You are", your_account()) # Out: You are rich! | |
| # Let's see what my_account and your_account are: | |
| print(my_account) # <function bank_account.<locals>.are_you_rich at 0x1079e2b90> | |
| print(your_account) # <function bank_account.<locals>.are_you_rich at 0x107a05b90> | |
| # The last number (address) might be different from what I've got, but its not important. The important thing | |
| # is the address is different for my_account and your_account. | |
| # It also shows you where the function is defined |
Ah yes, that is correct! I can't believe I've made that mistake lol.
Sure! I'll be happy to take a look at that :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The inner function can modify the variables
should be the inner function can 'access' the variables defined in the outer scope, but it cannot modify it
isn't it?
thanks for the explanation, I think I've formulated a good explanation, will email you to see if its suitable to share with the rest. :D