wraps裝飾器的使用

2022-07-11 14:21:11 字數 1184 閱讀 2648

使用functools模組提供的wraps裝飾器可以避免被裝飾的函式的特殊屬性被更改,如函式名稱__name__被更改。如果不使用該裝飾器,則會導致函式名稱被替換,從而導致端點(端點的預設值是函式名)出錯。

不使用wraps裝飾器時:

def test(func):

def decorated_function(*args, **kwargs):

"""decorated_function裡的注釋"""

print('hello')

return func(*args, **kwargs)

return decorated_function

@decorator

def function():

"""function裡的注釋"""

print('world')

function()

print(function.__name__)

print(function.__doc__)

輸出結果:

hello

world

decorated_function

decorated_function裡的注釋

使用wraps裝飾器時:

from functools import wraps

def test(func):

@wraps(func)

def decorated_function(*args, **kwargs):

"""decorated_function裡的注釋"""

print('hello')

return func(*args, **kwargs)

return decorated_function

@decorator

def function():

"""function裡的注釋"""

print('world')

function()

print(function.__name__)

print(function.__doc__)

輸出結果:

hello

world

function

function裡的注釋

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裝飾器中 wraps作用

裝飾器的作用 在不改變原有功能 的基礎上,新增額外的功能,如使用者驗證等。wraps view func 的作用 不改變使用裝飾器原有函式的結構 如name,doc 不使用 wraps裝飾器時候,看看 name doc 輸出的內容是什麼def decorator func this is decor...

python筆記36 裝飾器之wraps

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