import time
def log(func):
def wrapper(*args, **kw):
print('func %s() is running' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def now():
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
這是上一篇文章中用來分析的例子痒给。完整的寫法應(yīng)該是
import time
def log(func):
def wrapper(*args, **kw):
print('func %s() is running' % func.__name__)
return func(*args, **kw)
return wrapper
now = log(now)
def now():
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
之前我們學(xué)習(xí)高階函數(shù)的時(shí)候了解到了高階函數(shù)的特征之一就是它接收一個(gè)函數(shù)作為其參數(shù)泉坐。 現(xiàn)在我們補(bǔ)充另一個(gè)點(diǎn)就是搔扁,高階函數(shù)不僅接收函數(shù)作為參數(shù)劈彪,它還能將函數(shù)作為結(jié)果返回臣淤。
例如:
def lazy_sum(*args):
def sum():
ax = 0
for a in args:
ax = ax + a
return ax
return sum
# 當(dāng)調(diào)用lazy_sum時(shí)嗦锐,返回的是求和函數(shù)而不是結(jié)果
f = lazy_sum(1,2,3,3,4,5)
# 此時(shí) 打印 f 會(huì)得到一個(gè)函數(shù)
print(f)
#<function lazy_sum.<locals>.sum at 0x101c6ed90>
# 如果我們要獲取到 lazy_sum 的結(jié)果嫌松。可以調(diào)用 f
f()
我們每次調(diào)用 lazy_sum() 函數(shù)奕污,都會(huì)得到一個(gè)新的函數(shù)萎羔,即時(shí)傳入的參數(shù)相同,得到的結(jié)果也是不同的
現(xiàn)在回頭看我們的裝飾器 不用語法糖 @ 符號(hào)的寫法
首先裝飾器函數(shù) log
def log(func):
def wrapper(*args, **kw):
print('func %s() is running' % func.__name__)
return func(*args, **kw)
return wrapper
它接收一個(gè)函數(shù)碳默,并且再其內(nèi)部定一個(gè)了一個(gè)wrapper 函數(shù)贾陷,并將 wrapper 函數(shù)作為結(jié)果返回。
再來看調(diào)用裝飾器的方法
...
now = log(now)
# 第一個(gè) now 是變量名嘱根。 log方法中的 now 是下面定義的函數(shù) now髓废, 它被作為 參數(shù)傳入到 log 方法中。
def now():
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
我們是直接將 log 的返回賦值給了跟 函數(shù) now() 同名的變量 now该抒, 這么做就是為了后面的使用中不用再重復(fù)命名慌洪。