Home > Backend Development > Python Tutorial > Let's talk about Python decorators

Let's talk about Python decorators

coldplay.xixi
Release: 2020-09-03 16:33:45
forward
2203 people have browsed it

Let's talk about Python decorators

【Related learning recommendations: python tutorial

Decorator

  1. is essentially a function that accepts parameters as functions.
  2. Function: Add additional general functions to an already implemented method, such as logging, running timing, etc.

Example

Decorator without parameters, without @
# 不带参数的装饰器def deco_test(func):
    def wrapper(*args, **kwargs):
        print("before function")
        f = func(*args, **kwargs)
        print("after function")
        return f    return wrapperdef do_something(a,b,c):
    print(a)
    time.sleep(1)
    print(b)
    time.sleep(1)
    print(c)
    return aif __name__ == '__main__':
    # 不用@
    f = deco_test(do_something)("1","2","3")
Copy after login

Output:

before function
1
2
3
after function
Copy after login
Copy after login

Personal understanding:

is equivalent to putting two outputs outside the do_something function: before function and after function.

Decorator without parameters, use @
# 不带参数的装饰器def deco_test(func):
    def wrapper(*args, **kwargs):
        print("before function")
        f = func(*args, **kwargs)
        print("after function")
        return f    return wrapper

@deco_testdef do_something(a,b,c):
    print(a)
    time.sleep(1)
    print(b)
    time.sleep(1)
    print(c)
    return aif __name__ == '__main__':
    # 使用@
    f = do_something("1","2","3")
Copy after login

to output:

before function
1
2
3
after function
Copy after login
Copy after login

Personal understanding:

Equivalent to when executing the do_something function, because of @ reasons, we already know that there is a layer of decorator deco_test, so there is no need to write it separately deco_test(do_something) is gone.

Decorator with parameters
# 带参数的装饰器def logging(level):
    def wrapper(func):
        def inner_wrapper(*args, **kwargs):
            print("[{level}]: enter function {func}()".format(level=level, func=func.__name__))
            f = func(*args, **kwargs)
            print("after function: [{level}]: enter function {func}()".format(level=level, func=func.__name__))
            return f        return inner_wrapper    return wrapper

@logging(level="debug")def do_something(a,b,c):
    print(a)
    time.sleep(1)
    print(b)
    time.sleep(1)
    print(c)
    return aif __name__ == '__main__':
    # 使用@
    f = do_something("1","2","3")
Copy after login

Output:

[debug]: enter function do_something()
1
2
3
after function: [debug]: enter function do_something()
Copy after login

Personal understanding:

Decorator With a parameter level = "debug".

The outermost function logging() accepts parameters and applies them to the inner decorator function. The inner function wrapper() accepts a function as a parameter, and then places a decorator on the function. The key point here is that the decorator can use the parameters passed to logging().

Class Decorator
# 类装饰器class deco_cls(object):
    def __init__(self, func):
        self._func = func    def __call__(self, *args, **kwargs):
        print("class decorator before function")
        f = self._func(*args, **kwargs)
        print("class decorator after function")
        return f

@deco_clsdef do_something(a,b,c):
    print(a)
    time.sleep(1)
    print(b)
    time.sleep(1)
    print(c)
    return aif __name__ == '__main__':
    # 使用@
    f = do_something("1","2","3")
Copy after login

Output:

class decorator before function
1
2
3
class decorator after function
Copy after login

Personal understanding:

Use a decorator To wrap a function, return a callable instance. Therefore a class decorator is defined.

Two-layer decorator
# 不带参数的装饰器def deco_test(func):
    def wrapper(*args, **kwargs):
        print("before function")
        f = func(*args, **kwargs)
        print("after function")
        return f    return wrapper# 带参数的装饰器def logging(level):
    def wrapper(func):
        def inner_wrapper(*args, **kwargs):
            print("[{level}]: enter function {func}()".format(level=level, func=func.__name__))
            f = func(*args, **kwargs)
            print("after function: [{level}]: enter function {func}()".format(level=level, func=func.__name__))
            return f        return inner_wrapper    return wrapper

@logging(level="debug")@deco_testdef do_something(a,b,c):
    print(a)
    time.sleep(1)
    print(b)
    time.sleep(1)
    print(c)
    return aif __name__ == '__main__':
    # 使用@
    f = do_something("1","2","3")
Copy after login

Output:

[debug]: enter function wrapper()
before function
1
2
3
after function
after function: [debug]: enter function wrapper()
Copy after login

Personal understanding:

In functiondo_something() First put a layer of deco_test() decorator on the outside, and then put a layer of logging() decorator on the outside.

If you want to know more about programming learning, please pay attention to the php training column!

The above is the detailed content of Let's talk about Python decorators. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:oschina.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template