Python裝飾器中 wraps作用

2021-09-12 20:01:05 字數 1325 閱讀 4510

裝飾器的作用:在不改變原有功能**的基礎上,新增額外的功能,如使用者驗證等。

@wraps(view_func)的作用:不改變使用裝飾器原有函式的結構(如name, doc)

1.不使用@wraps裝飾器時候,看看__name__、__doc__輸出的內容是什麼

def

decorator

(func)

:"""this is decorator __doc__"""

def(

*args,

**kwargs)

:print()

return func(

*args,

**kwargs)

@decorator

deftest()

:"""this is test __doc__"""

print

("this is test method"

)print

("__name__: "

, test.__name__)

print

("__doc__: "

, test.__doc__)

"""結果:

"""

分析:對test()方法進行裝飾時候,實際上是

test = decorator(test)2. 使用@wraps裝飾器解決這個問題

from functools import wraps

defdecorator

(func)

:"""this is decorator __doc__"""

@wraps(func)

def(

*args,

**kwargs)

:print()

return func(

*args,

**kwargs)

@decorator

deftest()

:"""this is test __doc__"""

print

("this is test method"

)print

("__name__: "

, test.__name__)

print

("__doc__: "

, test.__doc__)

"""結果:

__name__: test

__doc__: this is test __doc__

"""

Python裝飾器中的 wraps的作用和使用

建立驗證使用者登陸功能裝飾器 from functools import wraps def user login confirm view func wraps view func 驗證使用者是否登陸 從session中獲取user id user id session.get user id u...

Python 裝飾器 wraps作用 使用記錄

def is login func def foo args,kwargs return func args,kwargs return foo deftest print 我是 test.name is login deftest1 print 我是 test1.name is login def...

python筆記36 裝飾器之wraps

前面一篇對python裝飾器有了初步的了解了,但是還不夠完美,領導看了後又提出了新的需求,希望執行的日誌能顯示出具體執行的哪個函式。name 用於獲取函式的名稱,doc 用於獲取函式的docstring內容 函式的注釋 import time def func a a func a hello pr...