簡體   English   中英

無需傳遞函數作為參數的Python裝飾器

[英]Python decorator without passing a function as argument

我正在學習編寫python裝飾器。 以下是兩個示例。

范例1:

def dec():
    def wrapper(func):
        print(func)
        return func

    return wrapper

@dec
def hello():
    print('hello')

范例2:

def dec(name):
    def wrapper(fn):
        print(fn)
        return fn
    return wrapper

@dec('a')
def hello(x):
    print(x)

所以我的問題是,為什么示例1拋出一個異常,即dec() takes 0 positional arguments but 1 was givendec() takes 0 positional arguments but 1 was given而示例2運行良好。

Bot示例不正確。 裝飾器的外部函數(在這種情況下為dec)必須接受一個參數,即裝飾函數。

因此,示例1應該如下所示:

def dec(func):
    def wrapper():
        print(func)
        return func

    return wrapper

@dec
def hello():
    print('hello')

hello()

示例2雖然不會立即崩潰,但如果您嘗試調用hello (修飾的函數),則會立即崩潰。 要讓裝飾器接受參數,您需要另一層嵌套。 因此,示例2應該如下所示:

def dec_args(name):
    def dec(func):
        def wrapper():
            print(func)
            print(name)
            return func

        return wrapper
    return dec

@dec_args('a')
def hello():
    print('hello')

hello()

內部裝飾器函數( wrapper )應該采用傳遞給裝飾函數( hello )的參數。 在這些情況下,您將沒有任何func 。另外請注意, wrapper函數實際上並不需要返回func wrapper本質上是func的替代。 這就是裝飾者所做的。 它們用裝飾器的內部函數替換您裝飾的函數(通過以裝飾的函數作為參數調用外部函數)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM