文章目錄
- 1.2 函數子產品化調用
- 2. 閉包函數
- 2.1 閉包定義:
- 2.2 閉包執行個體
- 2.3 閉包作用
- 2.3.1 當閉包執行完後,仍然能夠保持住目前的運作環境
- 2.3.2 閉包可以根據外部作用域的局部變量來得到不同的結果
- 2.4 使用閉包注意事項
- 2.4.1 閉包中是不能修改外部作用域的局部變量的
- 2.4.2 閉包函數傳回變量報錯
- 2.4.3 循環語句中的閉包函數
- 3. 遞歸函數
- 4. 嵌套函數
1.2 函數子產品化調用
帶時間戳日志格式的函數子產品化
$ mkdir log1
$ touch log1/__init__.py
$ vim log1/timestamp.py
#!/usr/bin/env python3
import time
def Timer(msg):
print(str(msg) + str(time.time() ) )
charge = 0.02
return charge
$ vim charge.py
#!/usr/bin/env python3
from log1 import timestamp
print("Press RETURN for the time (costs 2 cents).")
print("Press Q RETURN to quit.")
total = 0
while True:
kbd = input()
if kbd.lower() == "q":
print("You owe $" + str(total) )
exit()
else:
charge = timestamp.Timer("Time is ")
total = total+charge
[root@localhost time]$ python3.8 charge.py
Press RETURN for the time (costs 2 cents).
Press Q RETURN to quit.
Time is 1584882110.5468674
Time is 1584882111.1065543
q
You owe $0.04
[root@localhost time]$ python3.8 charge.py
Press RETURN for the time (costs 2 cents).
Press Q RETURN to quit.
Time is 1584882119.8083994
Time is 1584882120.2742803
Time is 1584882120.6922472
q
You owe $0.06
假如不調用子產品化函數方法
#!/usr/bin/env python3
import time
total = 0
def Timer(msg):
print(str(msg) + str(time.time() ) )
charge = .02
return charge
print("Press RETURN for the time (costs 2 cents).")
print("Press Q RETURN to quit.")
while True:
kbd = input()
if kbd.lower() == "q":
print("You owe $" + str(total) )
exit()
else:
charge = Timer("Time is ")
total = total+charge
[root@localhost time]# python3.8 charge2.py
Press RETURN for the time (costs 2 cents).
Press Q RETURN to quit.
Time is 1584882257.4966393
Time is 1584882258.4600565
q
You owe $0.04
2. 閉包函數
2.1 閉包定義:
如果在一個内部函數裡,對在外部作用域(但不是在全局作用域)的變量進行引用,那麼内部函數就被認為是閉包(closure)
2.2 閉包執行個體
def print_msg():
# print_msg 是外圍函數
msg = "zen of python"
def printer():
# printer 是嵌套函數
print(msg)
return printer
another = print_msg()
# 輸出 zen of python
another()
another 就是一個閉包,閉包本質上是一個函數,它有兩部分組成,printer 函數和變量 msg。閉包使得這些變量的值始終儲存在記憶體中。
閉包,顧名思義,就是一個封閉的包裹,裡面包裹着自由變量,就像在類裡面定義的屬性值一樣,自由變量的可見範圍随同包裹,哪裡可以通路到這個包裹,哪裡就可以通路到這個自由變量
2.3 閉包作用
2.3.1 當閉包執行完後,仍然能夠保持住目前的運作環境
比如說,如果你希望函數的每次執行結果,都是基于這個函數上次的運作結果。我以一個類似棋盤遊戲的例子來說明。假設棋盤大小為50*50,左上角為坐标系原點(0,0),我需要一個函數,接收2個參數,分别為方向(direction),步長(step),該函數控制棋子的運動。棋子運動的新的坐标除了依賴于方向和步長以外,當然還要根據原來所處的坐标點,用閉包就可以保持住這個棋子原來所處的坐标。
#!/usr/bin/python
#--coding:utf-8
origin = [0, 0] # 坐标系統原點
legal_x = [0, 50] # x軸方向的合法坐标
legal_y = [0, 50] # y軸方向的合法坐标
def create(pos=origin):
def player(direction,step):
# 這裡應該首先判斷參數direction,step的合法性,比如direction不能斜着走,step不能為負等
# 然後還要對新生成的x,y坐标的合法性進行判斷處理,這裡主要是想介紹閉包,就不詳細寫了。
new_x = pos[0] + direction[0]*step
new_y = pos[1] + direction[1]*step
pos[0] = new_x
pos[1] = new_y
#注意!此處不能寫成 pos = [new_x, new_y],原因在上文有說過
return pos
return player
player = create() # 建立棋子player,起點為原點
print player([1,0],10) # 向x軸正方向移動10步
print player([0,1],20) # 向y軸正方向移動20步
print player([-1,0],10) # 向x軸負方向移動10步
輸出為:
[10, 0]
[10, 20]
[0, 20]
2.3.2 閉包可以根據外部作用域的局部變量來得到不同的結果
這有點像一種類似配置功能的作用,我們可以修改外部的變量,閉包根據這個變量展現出不同的功能。比如有時我們需要對某些檔案的特殊行進行分析,先要提取出這些特殊行。
def make_filter(keep):
def the_filter(file_name):
file = open(file_name)
lines = file.readlines()
file.close()
filter_doc = [i for i in lines if keep in i]
return filter_doc
return the_filter
filter = make_filter("pass")
filter_result = filter("result.txt")
如果我們需要取得檔案"result.txt"中含有"pass"關鍵字的行,則可以這樣使用例子程式
2.4 使用閉包注意事項
2.4.1 閉包中是不能修改外部作用域的局部變量的
$ cat bibao3.py
#!/usr/bin/python
def out():
x = 0
def inn():
x = 1
print('inner x:', x)
print('out x:', x)
inn()
print('out x:', x)
out()
[root@localhost func]# python bibao3.py
('out x:', 0)
('inner x:', 1)
('out x:', 0)
2.4.2 閉包函數傳回變量報錯
def foo():
a = 1
def bar():
a = a + 1
return a
return bar
這段程式的本意是要通過在每次調用閉包函數時都對變量a進行遞增的操作。但在實際使用時
>>> c = foo()
>>> print c()
Traceback (most recent call last):
File "", line 1, in <module>
File "", line 4, in bar
UnboundLocalError: local variable 'a' referenced before assignment
這是因為在執行代碼 c = foo()時,python會導入全部的閉包函數體bar()來分析其的局部變量,python規則指定所有在指派語句左面的變量都是局部變量,則在閉包bar()中,變量a在指派符号"="的左面,被python認為是bar()中的局部變量。再接下來執行print c()時,程式運作至a = a + 1時,因為先前已經把a歸為bar()中的局部變量,是以python會在bar()中去找在指派語句右面的a的值,結果找不到,就會報錯。解決的方法很簡單
def foo():
a = [1]
def bar():
a[0] = a[0] + 1
return a[0]
return bar
隻要将a設定為一個容器就可以了。這樣使用起來多少有點不爽,是以在python3以後,在a = a + 1 之前,使用語句nonlocal a就可以了,該語句顯式的指定a不是閉包的局部變量。
2.4.3 循環語句中的閉包函數
在程式裡面經常會出現這類的循環語句,Python的問題就在于,當循環結束以後,循環體中的臨時變量i不會銷毀,而是繼續存在于執行環境中。還有一個python的現象是,python的函數隻有在執行時,才會去找函數體裡的變量的值。
$ cat bibao2.py
#!/usr/bin/python
flist = []
for i in range(3):
def foo(x): print x + i
flist.append(foo)
for f in flist:
f(2)
[root@localhost func]# python bibao2.py
4
4
4
可能有些人認為這段代碼的執行結果應該是2,3,4.但是實際的結果是4,4,4。這是因為當把函數加入flist清單裡時,python還沒有給i指派,隻有當執行時,再去找i的值是什麼,這時在第一個for循環結束以後,i的值是2,是以以上代碼的執行結果是4,4,4.
改寫一下函數的定義
$ cat bibao1.py
#!/usr/bin/python
flist = []
for i in range(3):
def foo(x,y=i): print x + y
flist.append(foo)
for f in flist:
f(2)
[root@localhost func]# python bibao1.py
2
3
4
3. 遞歸函數
$ cat digui.py
#!/usr/bin/python
def fat(n): #第一種方式
ret=1
for i in range(1,n+1):
ret=ret*i
return ret
print(fat(5))
def fact(n): #第二種方式
if n==1:
return 1
return n*fact(n-1)
print(fact(5))
[root@localhost func]# python digui.py
120
120
4. 嵌套函數
- 函數名可以指派
- 函數名可以作為函數參數,還可以作為傳回值
$ cat qiantao.py
#!/usr/bin/python
def f(n):
return n*n
def foo(a,b,func):
func(a)+func(b)
ret=func(a)+func(b)
return ret
print(foo(1,2,f))
[root@localhost func]$ python qiantao.py
5