首頁  >  文章  >  後端開發  >  如何在Python中保留修飾函數的簽名?

如何在Python中保留修飾函數的簽名?

Patricia Arquette
Patricia Arquette原創
2024-10-17 17:02:02574瀏覽

How to Preserve the Signature of Decorated Functions in Python?

保留裝飾函數的簽名

裝飾器是 Python 中用於擴展現有函數行為的強大工具。然而,當應用於函數時,所得的修飾函數通常會失去其原始文件和簽名。這可能會出現問題,尤其是在使用執行日誌記錄或參數轉換等常見任務的通用裝飾器時。

常見解決方法

一些常見解決方法包括:

  • 在裝飾函數的文件字串中包含簽名。
  • 為每個特定簽名建立專門的裝飾器。

使用裝飾器模組

一個更健壯的解決方案是使用裝飾器模組,它提供了一個名為@decorator.decorator的裝飾器函數。透過將此裝飾器套用到您自己的裝飾器函數中,您可以保留原始函數的簽名。

<code class="python">import decorator

@decorator.decorator
def args_as_ints(f, *args, **kwargs):
    args = [int(x) for x in args]
    kwargs = dict((k, int(v)) for k, v in kwargs.items())
    return f(*args, **kwargs)

@args_as_ints
def funny_function(x, y, z=3):
    """Computes x*y + 2*z"""
    return x*y + 2*z

print(funny_function("3", 4.0, z="5"))  # 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
#     Computes x*y + 2*z</code>

Python 3.4

在 Python 3.4 及更高版本中, functools.wraps() 函數可用於保留簽章。

<code class="python">import functools

def args_as_ints(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args = [int(x) for x in args]
        kwargs = dict((k, int(v)) for k, v in kwargs.items())
        return func(*args, **kwargs)
    return wrapper

@args_as_ints
def funny_function(x, y, z=3):
    """Computes x*y + 2*z"""
    return x*y + 2*z

print(funny_function("3", 4.0, z="5"))  # 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
#     Computes x*y + 2*z</code>

以上是如何在Python中保留修飾函數的簽名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn