简体   繁体   English

Python装饰器函数执行

[英]Python decorator function execution

I have below decorator demonstration code. 我有下面的装饰演示代码。 If I execute it without explicitly calling greet function, it is executing print statement inside decorator function and outputs Inside decorator . 如果我在没有显式调用greet函数的情况下执行它,它就会在decorator函数中执行print语句并输出Inside decorator

I am unable to understand this behavior of decorator. 我无法理解装饰器的这种行为。 How the time_decorator is called even if I didn't call greet function? 即使我没有调用greet函数,如何调用time_decorator

I am using Python 3. 我正在使用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 is executed during function decoration. time_decorator 功能装饰期间执行。 wrapper is not (this is function invoked when decorated greet() is called). wrapper不是(这是调用装饰的greet()时调用的函数)。

@ is just syntactic sugar. @只是语法糖。 Following code snippets are equivalent. 以下代码片段是等效的。

Decorator syntax: 装饰器语法:

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

Explicit decoration process - decorator is a function that returns new function based on another one. 显式装饰过程 - 装饰器是一个基于另一个返回新功能的函数。

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

greet = time_decorator(greet)

Decorators are called at start time (when the python interpreter reads the code as the program starts) , not at runtime (when the decorated function is actually called) . 装饰器在启动时调用(当python解释器在程序启动时读取代码) ,而不是在运行时 (实际调用装饰函数时)

At runtime, it is the wrapped function wrapper which is called and which itself calls the decorated function and returns its result. 在运行时,它是被调用的包装函数wrapper ,它自己调用装饰函数并返回其结果。

So this is totally normal that the print line gets executed. 因此,执行print行是完全正常的。

If, ie, you decorate 10 functions, you will see 10 times the print output. 如果,即装饰10个功能,您将看到10倍的打印输出。 No need to even call the decorated functions for this to happen. 甚至不需要调用装饰函数来实现这一点。

Move the print inside wrapper and this won't happen anymore. 移动print内部wrapper ,这将不再发生。

Decorators as well as metaclasses are part of what is called meta-programming (modify / create code, from existing code) . Decoratorsmetaclasses是所谓的元编程 (修改/创建代码,来自现有代码)的一部分 This is a really fascinating aspect of programming which takes time to understand but offers amazing possibilities. 这是一个非常迷人的编程方面,需要时间来理解,但提供了惊人的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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