匿名函數
當我們在傳入函數時,有些時候,不需要顯式地定義函數,直接傳入匿名函數更方便。
在Python中,對匿名函數提供了有限支持。還是以map()函數爲例,計算f(x)=x2時,除了定義一個f(x)的函數外,還可以直接傳入匿名函數:
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
通過對比可以看出,匿名函數lambda x: x * x實際上就是:
def f(x):
return x * x
關鍵字lambda表示匿名函數,冒號前面的x表示函數參數。
匿名函數有個限制,就是只能有一個表達式,不用寫return,返回值就是該表達式的結果。
用匿名函數有個好處,因爲函數沒有名字,不必擔心函數名衝突。此外,匿名函數也是一個函數對象,也可以把匿名函數賦值給一個變量,再利用變量來調用該函數:
>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28>
>>> f(5)
25
同樣,也可以把匿名函數作爲返回值返回,比如:
def build(x, y):
return lambda: x * x + y * y
練習
請用匿名函數改造下面的代碼:
# -*- coding: utf-8 -*-
----
def is_odd(n):
return n % 2 == 1
L = list(filter(is_odd, range(1, 20)))
----
print(L)
>>> list(filter(lambda x:x%2==1,range(1,20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
小結
Python對匿名函數的支持有限,只有一些簡單的情況下可以使用匿名函數。
裝飾器
由於函數也是一個對象,而且函數對象可以被賦值給變量,所以,通過變量也能調用該函數。
>>> def now():
... print('2015-3-25')
...
>>> f = now
>>> f()
2015-3-25
函數對象有一個name屬性,可以拿到函數的名字:
>>> now.__name__
'now'
>>> f.__name__
'now'
現在,假設我們要增強now()函數的功能,比如,在函數調用前後自動打印日誌,但又不希望修改now()函數的定義,這種在代碼運行期間動態增加功能的方式,稱之爲“裝飾器”(Decorator)。
本質上,decorator就是一個返回函數的高階函數。所以,我們要定義一個能打印日誌的decorator,可以定義如下:
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
觀察上面的log,因爲它是一個decorator,所以接受一個函數作爲參數,並返回一個函數。我們要藉助Python的@語法,把decorator置於函數的定義處:
@log
def now():
print('2015-3-25')
調用now()函數,不僅會運行now()函數本身,還會在運行now()函數前打印一行日誌:
>>> now()
call now():
2015-3-25
把@log放到now()函數的定義處,相當於執行了語句:
now = log(now)
由於log()是一個decorator,返回一個函數,所以,原來的now()函數仍然存在,只是現在同名的now變量指向了新的函數,於是調用now()將執行新函數,即在log()函數中返回的wrapper()函數。
wrapper()函數的參數定義是(*args, **kw),因此,wrapper()函數可以接受任意參數的調用。在wrapper()函數內,首先打印日誌,再緊接着調用原始函數。
如果decorator本身需要傳入參數,那就需要編寫一個返回decorator的高階函數,寫出來會更復雜。比如,要自定義log的文本:
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
這個3層嵌套的decorator用法如下:
@log('execute')
def now():
print('2015-3-25')
執行結果如下:
>>> now()
execute now():
2015-3-25
和兩層嵌套的decorator相比,3層嵌套的效果是這樣的:
now = log(‘execute’)(now)
我們來剖析上面的語句,首先執行log(‘execute’),返回的是decorator函數,再調用返回的函數,參數是now函數,返回值最終是wrapper函數。
以上兩種decorator的定義都沒有問題,但還差最後一步。因爲我們講了函數也是對象,它有name等屬性,但你去看經過decorator裝飾之後的函數,它們的name已經從原來的’now’變成了’wrapper’:
>>> now.__name__
'wrapper'
因爲返回的那個wrapper()函數名字就是’wrapper’,所以,需要把原始函數的name等屬性複製到wrapper()函數中,否則,有些依賴函數簽名的代碼執行就會出錯。
不需要編寫wrapper.name = func.name這樣的代碼,Python內置的functools.wraps就是幹這個事的,所以,一個完整的decorator的寫法如下:
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
或者針對帶參數的decorator:
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
import functools是導入functools模塊。模塊的概念稍候講解。現在,只需記住在定義wrapper()的前面加上@functools.wraps(func)即可。
通俗理解裝飾器
def 煉丹爐(func): # func就是‘孫悟空’這個函數
def 變身(*args, **kwargs): #*args, **kwargs就是‘孫悟空’的參數列表,這裏的‘孫悟空’函數沒有傳參數,我們寫上也不影響,建議都寫上
print('有火眼金睛了') # 加特效,增加新功能,比如孫悟空的進了煉丹爐後, 有了火眼金睛技能
return func(*args, **kwargs) #保留原來的功能,原來孫悟空的技能,如吃桃子
return 變身 # 煉丹成功,更強大的,有了火眼金睛技能的孫悟空出世
@煉丹爐
def 孫悟空():
print('吃桃子')
孫悟空()
# 輸出:
# 有火眼金睛了
# 吃桃子
userAge = 40
def canYou(func):
def decorator(*args, **kwargs):
if userAge > 1 and userAge < 10: #加年齡限制,只允許1-10歲纔可以看動畫片
return func(*args, **kwargs)
print('你的年齡不符合要求,不能看')
return decorator
@canYou
def play():
print('開始播放動畫片 《喜洋洋和灰太狼》')
play()
# 輸出
# 你的年齡不符合要求,不能看
# 你可以修改上面的 userAge 爲9 試試
練習
請設計一個decorator,它可作用於任何函數上,並打印該函數的執行時間:
import time,functools
def printcalltime(fun):
@functools.wraps(fun)
def wrapper(*args, **kw):
start = time.time()
res = fun(*args, **kw)
end = time.time()
print('%s excute time = %d ms !' %(fun.__name__, (end - start) * 1000))
return res
return wrapper
@printcalltime
def print1():
time.sleep(2) #time.sleep()函數推遲調用線程的運行,可通過參數secs指秒數,表示進程掛起的時間。語法:time.sleep(t),t表示推遲執行的秒數
print1()
print(print1.__name__)
結果:
F:\>python hello.py
print1 excute time = 2000 ms !
print1
小結
在面向對象(OOP)的設計模式中,decorator被稱爲裝飾模式。OOP的裝飾模式需要通過繼承和組合來實現,而Python除了能支持OOP的decorator外,直接從語法層次支持decorator。Python的decorator可以用函數實現,也可以用類實現。
decorator可以增強函數的功能,定義起來雖然有點複雜,但使用起來非常靈活和方便。
練習
請編寫一個decorator,能在函數調用的前後打印出’begin call’和’end call’的日誌。
import time,functools
def log(fun):
@functools.wraps(fun)
def wrapper(*args, **kw):
print('begin call')
r= fun(*args, **kw)
print('end call')
return r
return wrapper
@log
def print1():
print('36')
print1()
結果:
F:\>python hello.py
begin call
36
end call
思考
能否寫出一個@log的decorator,使它既支持:
@log
def f():
pass
又支持:
@log(‘execute’)
def f():
pass
第一種:
import functools
def log(str=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
if(str!= None):
print('%s ' %(str))
else:
print('%s' %(func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def print1():
print('36')
@log()
def print2():
print('236')
print1()
print2()
結果:
F:\>python hello.py
execute
36
print2
236
第二種:
import functools
def log(param):
if callable(param): #callable() 函數用於檢查一個對象是否是可調用的。
def wrapper(*args, **kw):
print('%s' % (param.__name__,))
param(*args, **kw)
return wrapper
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (param, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log
def print1():
print("2018")
@log("execute")
def print2():
print("2018")
print1()
print2()
結果:
F:\>python hello.py
print1
2018
execute print2():
2018