Skip to content

Commit 1abe435

Browse files
committed
Python 3 global和nonlocal作用域
1 parent 4b8b7ac commit 1abe435

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

‎scope.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def scope_test():
2+
def do_local():
3+
spam = "local spam"
4+
def do_nonlocal():
5+
nonlocal spam
6+
spam = "nonlocal spam"
7+
def do_global():
8+
global spam
9+
spam = "global spam"
10+
11+
spam = "test spam"
12+
do_local()
13+
print("After local assignment:", spam)
14+
do_nonlocal()
15+
print("After nonlocal assignment:", spam)
16+
do_global()
17+
print("After global assignment:", spam)
18+
19+
scope_test()
20+
print("In global scope:", spam)
21+
22+
def make_counter():
23+
count = 0
24+
def counter():
25+
nonlocal count
26+
count += 1
27+
return count
28+
return counter
29+
30+
def make_counter_test():
31+
mc = make_counter()
32+
print(mc())
33+
print(mc())
34+
print(mc())
35+
36+
make_counter_test()

0 commit comments

Comments
 (0)