@@ -746,15 +746,58 @@ This prints `[2]` as the value of `f(x)` and *same* for `x`.
|
746 | 746 | Here's what happens |
747 | 747 | |
748 | 748 | * `f` is registered as a function in the global namespace |
| 749 | + |
| 750 | +```{figure} /_static/lecture_specific/oop_intro/mutable1.png |
| 751 | +:figclass: auto |
| 752 | +``` |
| 753 | + |
749 | 754 | * `x` bound to `[1]` in the global namespace |
| 755 | + |
| 756 | +```{figure} /_static/lecture_specific/oop_intro/mutable2.png |
| 757 | +:figclass: auto |
| 758 | +``` |
| 759 | + |
750 | 760 | * The call `f(x)` |
751 | 761 | * Creates a local namespace |
752 | 762 | * Adds `x` to the local namespace, bound to `[1]` |
| 763 | + |
| 764 | +```{figure} /_static/lecture_specific/oop_intro/mutable3.png |
| 765 | +:figclass: auto |
| 766 | +``` |
| 767 | + |
| 768 | +```{note} |
| 769 | +The global `x` and the local `x` refer to the same `[1]` |
| 770 | +``` |
| 771 | + |
| 772 | +We can see the identity of local `x` and the identity of global `x` are the same |
| 773 | + |
| 774 | +```{code-cell} python3 |
| 775 | +def f(x): |
| 776 | + x[0] = x[0] + 1 |
| 777 | + print(f'the identity of local x is {id(x)}') |
| 778 | + return x |
| 779 | + |
| 780 | +x = [1] |
| 781 | +print(f'the identity of global x is {id(x)}') |
| 782 | +print(f(x), x) |
| 783 | +``` |
| 784 | + |
| 785 | +* Within `f(x)` |
753 | 786 | * The list `[1]` is modified to `[2]` |
754 | 787 | * Returns the list `[2]` |
755 | | -* The local namespace is deallocated, and local `x` is lost |
756 | | -* Global `x` has been modified |
757 | 788 | |
| 789 | +```{figure} /_static/lecture_specific/oop_intro/mutable4.png |
| 790 | +:figclass: auto |
| 791 | +``` |
| 792 | +* The local namespace is deallocated, and the local `x` is lost |
| 793 | + |
| 794 | +```{figure} /_static/lecture_specific/oop_intro/mutable5.png |
| 795 | +:figclass: auto |
| 796 | +``` |
| 797 | + |
| 798 | +If you want to modify the local `x` and the global `x` separately, you can create a [*copy*](https://docs.python.org/3/library/copy.html) of the list and assign the copy to the local `x`. |
| 799 | + |
| 800 | +We will leave this for you to explore. |
758 | 801 | |
759 | 802 | |
760 | 803 | ## Summary |
|