簡體   English   中英

Python裝飾器函數執行

[英]Python decorator function execution

我有下面的裝飾演示代碼。 如果我在沒有顯式調用greet函數的情況下執行它,它就會在decorator函數中執行print語句並輸出Inside decorator

我無法理解裝飾器的這種行為。 即使我沒有調用greet函數,如何調用time_decorator

我正在使用Python 3。

def time_decorator(original_func):
    print('Inside decorator')
    def wrapper(*args, **kwargs):
        start = time.clock()
        result = original_func(*args, **kwargs)
        end = time.clock()
        print('{0} is executed in {1}'.format(original_func.__name__, end-start))
        return result
    return wrapper


@time_decorator
def greet(name):
    return 'Hello {0}'.format(name)

time_decorator 功能裝飾期間執行。 wrapper不是(這是調用裝飾的greet()時調用的函數)。

@只是語法糖。 以下代碼片段是等效的。

裝飾器語法:

@time_decorator
def greet(name):
    return 'Hello {0}'.format(name)

顯式裝飾過程 - 裝飾器是一個基於另一個返回新功能的函數。

def greet(name):
    return 'Hello {0}'.format(name)

greet = time_decorator(greet)

裝飾器在啟動時調用(當python解釋器在程序啟動時讀取代碼) ,而不是在運行時 (實際調用裝飾函數時)

在運行時,它是被調用的包裝函數wrapper ,它自己調用裝飾函數並返回其結果。

因此,執行print行是完全正常的。

如果,即裝飾10個功能,您將看到10倍的打印輸出。 甚至不需要調用裝飾函數來實現這一點。

移動print內部wrapper ,這將不再發生。

Decoratorsmetaclasses是所謂的元編程 (修改/創建代碼,來自現有代碼)的一部分 這是一個非常迷人的編程方面,需要時間來理解,但提供了驚人的可能性。

暫無
暫無

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

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