函數也是對象
要理解Python裝飾器,首先要明白在Python中,函數也是一種對象,因此可以把定義函數時的函數名看作是函數對象的一個引用。既然是引用,因此可以將函數賦值給一個變量,也可以把函數作為一個參數傳遞或返回。同時,函數體中也可以再定義函數。
裝飾器本質
可以通過編寫一個純函數的例子來還原裝飾器所要做的事。
def decorator(func):    def wrap():    print("Doing someting before executing func()")    func()    print("Doing someting after executing func()")  return wrapdef fun_test():  print("func")fun_test = decorator(fun_test)fun_test()# Output:# Doing someting before executing func()# func# Doing someting after executing func()fun_test所指向的函數的引用傳遞給decorator()函數
decorator()函數中定義了wrap()子函數,這個子函數會調用通過func引用傳遞進來的fun_test()函數,并在調用函數的前后做了一些其他的事情
decorator()函數返回內部定義的wrap()函數引用
fun_test接收decorator()返回的函數引用,從而指向了一個新的函數對象
通過fun_test()調用新的函數執行wrap()函數的功能,從而完成了對fun_test()函數的前后裝飾
Python中使用裝飾器
在Python中可以通過@符號來方便的使用裝飾器功能。
def decorator(func):    def wrap():    print("Doing someting before executing func()")    func()    print("Doing someting after executing func()")  return wrap@decoratordef fun_test():  print("func")fun_test()# Output:# Doing someting before executing func()# func# Doing someting after executing func()裝飾的功能已經實現了,但是此時執行:
print(fun_test.__name__)# Output:# wrap
fun_test.__name__已經變成了wrap,這是應為wrap()函數已經重寫了我們函數的名字和注釋文檔。此時可以通過functools.wraps來解決這個問題。wraps接受一個函數來進行裝飾,并加入了復制函數名稱、注釋文檔、參數列表等等功能。這可以讓我們在裝飾器里面訪問在裝飾之前的函數的屬性。
更規范的寫法:
from functools import wrapsdef decorator(func):  @wraps(func)  def wrap():    print("Doing someting before executing func()")    func()    print("Doing someting after executing func()")  return wrap@decoratordef fun_test():  print("func")fun_test()print(fun_test.__name__)# Output:# Doing someting before executing func()# func# Doing someting after executing func()# fun_test帶參數的裝飾器
通過返回一個包裹函數的函數,可以模仿wraps裝飾器,構造出一個帶參數的裝飾器。
from functools import wrapsdef loginfo(info='info1'):  def loginfo_decorator(func):    @wraps(func)    def wrap_func(*args, **kwargs):      print(func.__name__ + ' was called')      print('info: %s' % info)            return func(*args, **kwargs)    return wrap_func  return loginfo_decorator  @loginfo()def func1():  pass  func1()# Output:# func1 was called# info: info1@loginfo(info='info2')def func2():  passfunc2()# Output:# func2 was called# info: info2            
| 
 
 | 
新聞熱點
疑難解答