1. 函數(shù)引用
def test1():
print("--- in test1 func----")
# 調(diào)用函數(shù)
test1()
# 引用函數(shù)
ret = test1
print(id(ret))
print(id(test1))
#通過引用調(diào)用函數(shù)
ret()
運(yùn)行結(jié)果:
--- in test1 func----
140212571149040
140212571149040
--- in test1 func----
2. 什么是閉包
# 定義一個(gè)函數(shù)
def test(number):
# 在函數(shù)內(nèi)部再定義一個(gè)函數(shù)魂爪,并且這個(gè)函數(shù)用到了外邊函數(shù)的變量绍刮,那么將這個(gè)函數(shù)以及用到的一些變量稱之為閉包
def test_in(number_in):
print("in test_in 函數(shù), number_in is %d" % number_in)
return number+number_in
# 其實(shí)這里返回的就是閉包的結(jié)果
return test_in
# 給test函數(shù)賦值览爵,這個(gè)20就是給參數(shù)number
ret = test(20)
# 注意這里的100其實(shí)給參數(shù)number_in
print(ret(100))
#注 意這里的200其實(shí)給參數(shù)number_in
print(ret(200))
運(yùn)行結(jié)果:
in test_in 函數(shù), number_in is 100
120
in test_in 函數(shù), number_in is 200
220
3. 看一個(gè)閉包的實(shí)際例子:
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))
這個(gè)例子中烈拒,函數(shù)line與變量a,b構(gòu)成閉包嚷量。在創(chuàng)建閉包的時(shí)候陋桂,我們通過line_conf的參數(shù)a,b說明了這兩個(gè)變量的取值,這樣蝶溶,我們就確定了函數(shù)的最終形式(y = x + 1和y = 4x + 5)嗜历。我們只需要變換參數(shù)a,b,就可以獲得不同的直線表達(dá)函數(shù)抖所。由此梨州,我們可以看到,閉包也具有提高代碼可復(fù)用性的作用田轧。
如果沒有閉包暴匠,我們需要每次創(chuàng)建直線函數(shù)的時(shí)候同時(shí)說明a,b,x。這樣傻粘,我們就需要更多的參數(shù)傳遞每窖,也減少了代碼的可移植性帮掉。
注意點(diǎn):
由于閉包引用了外部函數(shù)的局部變量,則外部函數(shù)的局部變量沒有及時(shí)釋放岛请,消耗內(nèi)存
4. 修改外部函數(shù)中的變量
python3的方法
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())
python2的方法
def counter(start=0):
count=[start]
def incr():
count[0] += 1
return count[0]
return incr
c1 = closeure.counter(5)
print(c1()) # 6
print(c1()) # 7
c2 = closeure.counter(100)
print(c2()) # 101
print(c2()) # 102