Python的闭包
什么是閉包
#定義一個函數
def test(number):
#在函數內部再定義一個函數,并且這個函數用到了外邊函數的變量,那么將這個函數以及用到的一些變量稱之為閉包
def test_in(number_in):
print("in test_in 函數, number_in is %d"%number_in)
return number+number_in #其實這里返回的就是閉包的結果 return test_in #給test函數賦值,這個20就是給參數
numberret = test(20)#注意這里的100其實給參數
number_inprint(ret(100))#注意這里的200其實給參數
number_inprint(ret(200))
運行結果:
in test_in 函數, number_in is 100
120
in test_in 函數, number_in is 200
220
內部函數對外部函數作用域里變量的引用(非全局變量),則稱內部函數為閉包。
理解閉包
def counter(start=0):
count=[start]
def incr():
count[0] += 1
return count[0]
return incr
?
c1=counter(5)
print(c1())
print(c1())
c2=counter(100)
print(c2())
print(c2())
運行結果
6
7
101
102
函數返回給變量后,函數不會釋放,當改變函數中的變量是,下次調用依舊是這個變量
使用nonlocal訪問外部函數的局部變量(python3)
def counter(start=0):
def incr():
nonlocal start
start += 1
return start
return incr
?
c1 = counter(5)
print(c1())
print(c1())
閉包在實際中的使用
def line_conf(a, b):
def line(x):
return a*x + b
return line
?
line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
print(line1(5))
print(line2(5))
相當于先設定好變量值,當使用的時候就可以直接傳遞關注的參數就可以了
總結
- 上一篇: 西游日记7/27
- 下一篇: python表示当前目录_从Python