首页 > 编程语言 > 详细

python里的闭包

时间:2020-04-17 10:42:59      阅读:52      评论:0      收藏:0      [点我收藏+]
 1 #定义一个函数
 2 def test(number): 
 3 
 4     #在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么称里面 的这个函数为闭包 
 5 def test_in(number_in):
 6     print("in test_in 函数, number_in is %d"%number_in)
 7     return number+number_in
 8     #其实这里返回的就是闭包的结果
 9     return test_in
10 
11 
12 #给test函数赋值,这个20就是给参数number
13 ret = test(20) 
14 
15 #注意这里的100其实给参数number_in
16 print(ret(100))
17 
18 #注意这里的200其实给参数number_in
19 print(ret(200))
20 
21 运行结果:
22 in test_in 函数, number_in is 100
23 120 
24 
25 in test_in 函数, number_in is 200
26 220
#内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包。
# closure.py
def counter(start=0): 
    count=[start] 
    def incr(): 
        count[0] += 1 
        return count[0]
     return incr 

#启动python解释器
>>>import closeure
>>>c1=closeure.counter(5) 
>>>print(c1())
6
>>>print(c1())
7
>>>c2=closeure.counter(100)
>>>print(c2())
101
>>>print(c2())
102

#nonlocal访问外部函数的局部变量
def counter(start=0):
     def incr():
         nonlocal start
        start += 1 
        return start
     return incr

c1 = counter(5)
print(c1())
print(c1())

c2 = counter(50)
print(c2())
print(c2())

print(c1())
print(c1())

print(c2())
print(c2())            

 

python里的闭包

原文:https://www.cnblogs.com/Yanss/p/12718094.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!