回答編集履歴
2
追記
answer
CHANGED
@@ -84,4 +84,10 @@
|
|
84
84
|
In global scope:
|
85
85
|
global spam
|
86
86
|
139676165093680
|
87
|
-
```
|
87
|
+
```
|
88
|
+
|
89
|
+
**追記: **
|
90
|
+
よく考えたら (むしろよく考えなくても) idを見る必要は無いですね。
|
91
|
+
せっかくspamの値を切り替えているのですから...
|
92
|
+
|
93
|
+
無意味な実験をこっそり消すのもなんとも虚しいので、残してはおきます。
|
1
追記
answer
CHANGED
@@ -20,4 +20,68 @@
|
|
20
20
|
|
21
21
|
> 変数 spam がグローバル変数になったのだから、グローバル変数 spam に"global spam"を代入した
|
22
22
|
|
23
|
-
グローバルな空間にあるspamをいくら書き換えたところで、2番のspam には影響しません。
|
23
|
+
グローバルな空間にあるspamをいくら書き換えたところで、2番のspam には影響しません。
|
24
|
+
|
25
|
+
実験
|
26
|
+
---
|
27
|
+
idを見てみるとなかなか面白いですね。
|
28
|
+
```Python
|
29
|
+
def debug_print(message, obj):
|
30
|
+
print(message)
|
31
|
+
print(f'\t{obj}\n\t{id(obj)}')
|
32
|
+
|
33
|
+
def scope_test():
|
34
|
+
def do_local():
|
35
|
+
spam = "local spam"
|
36
|
+
debug_print("In do_local:", spam)
|
37
|
+
|
38
|
+
def do_nonlocal():
|
39
|
+
nonlocal spam
|
40
|
+
spam = "nonlocal spam"
|
41
|
+
debug_print("In do_nonlocal:", spam)
|
42
|
+
|
43
|
+
def do_global():
|
44
|
+
global spam
|
45
|
+
spam = "global spam"
|
46
|
+
debug_print("In do_global:", spam)
|
47
|
+
|
48
|
+
spam = "test spam"
|
49
|
+
debug_print("Before any assignment:", spam)
|
50
|
+
do_local()
|
51
|
+
debug_print("After local assignment:", spam)
|
52
|
+
do_nonlocal()
|
53
|
+
debug_print("After nonlocal assignment:", spam)
|
54
|
+
do_global()
|
55
|
+
debug_print("After global assignment:", spam)
|
56
|
+
|
57
|
+
scope_test()
|
58
|
+
debug_print("In global scope:", spam)
|
59
|
+
```
|
60
|
+
|
61
|
+
**実行結果** [Wandbox](https://wandbox.org/permlink/HMgzVhh6wCVUg2zs)
|
62
|
+
```plain
|
63
|
+
Before any assignment:
|
64
|
+
test spam
|
65
|
+
139676165093808
|
66
|
+
In do_local:
|
67
|
+
local spam
|
68
|
+
139676165093296
|
69
|
+
After local assignment:
|
70
|
+
test spam
|
71
|
+
139676165093808
|
72
|
+
In do_nonlocal:
|
73
|
+
nonlocal spam
|
74
|
+
139676165093488
|
75
|
+
After nonlocal assignment:
|
76
|
+
nonlocal spam
|
77
|
+
139676165093488
|
78
|
+
In do_global:
|
79
|
+
global spam
|
80
|
+
139676165093680
|
81
|
+
After global assignment:
|
82
|
+
nonlocal spam
|
83
|
+
139676165093488
|
84
|
+
In global scope:
|
85
|
+
global spam
|
86
|
+
139676165093680
|
87
|
+
```
|