Skip to content

Commit 6347e16

Browse files
committed
python中的闭包 for python 3.x
UnboundLocalError: local variable 'count' referenced before assignment. 什么意思?就是说conut这个变量你没有定义就直接引用了,我不知道这是个什么东西,程序就崩溃了.于是,再python3里面,引入了一个关键字:nonlocal,这个关键字是干什么的?就是告诉python程序,我的这个count变量是再外部定义的,你去外面找吧.然后python就去外层函数找,然后就找到了count=0这个定义和赋值,程序就能正常执行了.
1 parent 8255a5e commit 6347e16

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

closure.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,28 @@
11
def hellocounter (name):
2-
count=[0]
2+
count=0 #PYTHON 2.x 中,要写count=[0]
33
def counter():
4-
count[0]+=1
5-
print('Hello,',name,',',count[0],' access!')
4+
nonlocal count #PYTHON 2.x 中,此行和下一行要换成count[0]+=1
5+
count+=1
6+
print('Hello,',name,',',count,' access!')#PYTHON 2.x 中请自觉换成str(count[0])
67
return counter
78

89
hello = hellocounter('ma6174')
910
hello()
1011
hello()
1112
hello()
1213

14+
'''
15+
执行结果
16+
>>> hello()
17+
Hello, ma6174 , 1 access!
18+
>>> hello()
19+
Hello, ma6174 , 2 access!
20+
>>> hello()
21+
Hello, ma6174 , 3 access!
22+
'''
23+
##为什么PYTHON 2.x中不直接写count而用list?这是python2的一个bug,如果用count话,会报这样一个错误:
24+
##UnboundLocalError: local variable 'count' referenced before assignment.
25+
1326
def make_adder(addend):
1427
def adder(augend):
1528
return augend + addend

0 commit comments

Comments
 (0)