This is the lecture note of CS61A - Lecture 14.
Mutable Functions
Mutable functions' behaviors vary over time. Let's see an example.
- Let's model a bank account that has a balance of $100
1 | 25) withdraw( |
Environment Diagram
The implementation is as follows:
1 | # SOLUTION |
Notice the keyword nonlocal
in line 6. We will talk about it in the next section.
Non-local Assignment
However, there is a quirk in Python, see the following code.
1 | def make_withdraw(balance): |
✨ Summary: You need nonlocal
if you want to change values declared in parent frames. You don't need nonlocal
if you just want to look up values in parent frames of the current environment. (I recommend doing this disc to have better understanding of nonlocal.)
Mutable Values & Persistent Local State
However, mutable values can be changed without a nonlocal statement.
Let's see an example.
1 | def make_withdraw_list(balance): |
Example
Let's use an example to finish today's lecture.
1 | def f(x): |
Try to work through this program before seeing the answer.
Here is the answer.
1 | 1) a = f( |