简体   繁体   中英

Returning wrapper in decorator functions

I have a question about returning the wrapper why am i have to return it and where am i returning this? i know when i return wrapper it returns a pointer but where and what is the reason for that. shouldn't i call it in deco function like def deco(fun): ......... wrapper().

import  time

def deco(fun) :
    def wrapper(*args) :
        ba = time.time()

        giden = fun(*args)

        so = time.time()

        print(f"{so-ba} saniye geçti")

        return giden
    return wrapper


@deco
def ortalama (liste):
    t = 0
    for i in liste:
        t += i
    return t

liste = list(range(0,10))
a = ortalama(liste)
print(a)

deco takes a function as parameter and returns a function.

When you apply it the ortalama function is replaced with deco(ortalama) .

Decorator functions encapsulate the target functions and can manipulate their input and output values. Returning inner wrapper function replaces within the target function.

With decorator annotation, the function is changed with a wrapper function.

> print(ortalama)

<function deco.<locals>.wrapper at 0x7f7d6beea048>

Without decorator, the function stills as defined

> print(ortalama)

<function ortalama at 0x7f7d6beea158>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM