一、閉包概述
(1) 概述
def test(num):
def test_in(num_in):
print("in test_in 函數 num_in is %d "% num_in)
return num + num_in
return test_in
"""在函數內部再定義一個函數,並且這個函數用到外面函數的變量,那麼將這個函數以及用到的一些變量成爲閉包"""
(2) 閉包執行過程
def test(num):
print("--1--")
def test_in(num_in):
print("--2--")
print("in test_in 函數 num_in is %d "% num_in)
return num + num_in
print("--3--")
return test_in # 表述函數test_in()的引用
# 調用函數
test(50)
# 輸出結果
--1--
--3--
# 發現中間的代碼塊並沒有執行,但是它返回了函數test_in()的引用。
“”“如果要想執行test_in()函數,那麼就需要一個變量來接受內部函數的引用,即”“”
par = test(50) # 這部分相當於test_in
par() # 這部分相當於test_in(),即執行內部函數
二、閉包應用
“”“這個例子中函數line與變量a,b 構成了閉包”“”
def line_conf(a,b):
def line(x):
return a * x + b
return line
"""利用閉包的好處是隻定義一次a, b 的值就可以來計算不同的x。如果傳統的方法計算 a*x + b 那麼每次都要傳入三個參數,顯得不方便。"""
line1 = line_conf(1, 1)
print(line1(5))
print(line1(2))
print(line1(3))
line2 = line_conf(4, 5)
print(line2(5))
print(line2(2))
print(line2(3))