1. 基本介紹
-
定義
在函數調用前後自動打印日誌,稱之爲“裝飾器”(Decorator) -
本質
decorator就是一個 返回函數的高階函數,是返回函數的一種用途。
將業務code與日誌code解碼的過程。輸入的變量是一個函數:負責處理業務 -
使用方式
利用python語法糖 @語法 -
核心點
Python中,一切皆爲對象,函數也不例外
2. 理解函數
2.1 函數也是對象
def hi(name="yasoob"):
return "hi " + name
print(hi())
# output: 'hi yasoob'
# 我們甚至可以將一個函數賦值給一個變量,比如
greet = hi
# 我們這裏沒有在使用小括號,因爲我們並不是在調用hi函數
# 而是在將它放在greet變量裏頭。我們嘗試運行下這個
print(greet())
# output: 'hi yasoob'
# 如果我們刪掉舊的hi函數,看看會發生什麼!
del hi
print(hi())
#outputs: NameError
print(greet())
#outputs: 'hi yasoob'
2.2 嵌套函數
def hi(name="yasoob"):
print("now you are inside the hi() function")
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
print(greet())
print(welcome())
print("now you are back in the hi() function")
hi()
#output:now you are inside the hi() function
# now you are in the greet() function
# now you are in the welcome() function
# now you are back in the hi() function
# 上面展示了無論何時你調用hi(), greet()和welcome()將會同時被調用。
# 然後greet()和welcome()函數在hi()函數之外是不能訪問的,比如:
greet()
#outputs: NameError: name 'greet' is not defined
2.3 返回結果爲函數
從函數中返回函數.其實並不需要在一個函數裏去執行另一個函數,我們也可以將其作爲輸出返回出來
def hi(name="yasoob"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "yasoob":
return greet
else:
return welcome
a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>
#上面清晰地展示了`a`現在指向到hi()函數中的greet()函數
#現在試試這個
print(a())
#outputs: now you are in the greet() function
在 if/else 語句中我們返回 greet 和 welcome,而不是 greet() 和 welcome()。爲什麼那樣?這是因爲當你把一對小括號放在後面,這個函數就會執行;然而如果你不放括號在它後面,那它可以被到處傳遞,並且可以賦值給別的變量而不去執行它。
再稍微多解釋點細節。
當我們寫下 a = hi(),hi() 會被執行,而由於 name 參數默認是 yasoob,所以函數 greet 被返回了。如果我們把語句改爲 a = hi(name = “ali”),那麼 welcome 函數將被返回。我們還可以打印出 hi()(),這會輸出 now you are in the greet() function。
2.4 函數作爲輸入參數
def hi():
return "hi yasoob!"
def doSomethingBeforeHi(func):
print("I am doing some boring work before executing hi()")
print(func())
doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
# hi yasoob!
3.創建裝飾器
from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)#
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
函數不需要做任何修改,只需在定義的地方加上裝飾器,調用的時候還是和以前一樣,如果我們有其他的類似函數,我們可以繼續調用裝飾器來修飾函數,而不用重複修改函數或者增加新的封裝。這樣,我們就提高了程序的可重複利用性,並增加了程序的可讀性
4.帶參數的裝飾器
裝飾器在 Python 使用如此方便都要歸因於 Python 的函數能像普通的對象一樣能作爲參數傳遞給其他函數,可以被賦值給其他變量,可以作爲返回值,可以被定義在另外一個函數內。
想想這個問題,難道@wraps不也是個裝飾器嗎?但是,它接收一個參數,就像任何普通的函數能做的那樣。那麼,爲什麼我們不也那樣做呢? 這是因爲,當你使用@my_decorator語法時,你是在應用一個以單個函數作爲參數的一個包裹函數。記住,Python裏每個東西都是一個對象,而且這包括函數!記住了這些,我們可以編寫一下能返回一個包裹函數的函數。
from functools import wraps
def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打開logfile,並寫入內容
with open(logfile, 'a') as opened_file:
# 現在將日誌打到指定的logfile
opened_file.write(log_string + '\n')
return func(*args, **kwargs)
return wrapped_function
return logging_decorator
@logit()
def myfunc1():
pass
myfunc1()
# Output: myfunc1 was called
# 現在一個叫做 out.log 的文件出現了,裏面的內容就是上面的字符串
@logit(logfile='func2.log')
def myfunc2():
pass
myfunc2()
# Output: myfunc2 was called
# 現在一個叫做 func2.log 的文件出現了,裏面的內容就是上面的字符串
5.裝飾器的應用-監控日誌
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logit
def addition_func(x):
"""Do some math."""
return x + x
result = addition_func(4)
# Output: addition_func was called