Python Initial Python Decorator

Python Initial Python Decorator

1. The principle of openness and closure:

(1) Opening up code extensions

It is impossible for any program to think about all its functions at the beginning of its design without any updates or modifications in the future. So we have to allow code to expand and add new functions.

(2) Modifying source code is closed

When we write a function that has been delivered to other people for use, if we modify the function internally or change the way the function is called, it is likely to affect other users who are already using the function.

Without modifying the source code and invocation methods, the principle of open and closed is to add additional functions.

2. Decorators:

Additional functionality is added to the decorated function without changing its source code and calling method.

(1) Primary knowledge of decorative devices:

Decoration (Extra Function) Device (Tool: Function)

import time

def index():
    time.sleep(2)  #
    print("This is Xiao Ming's function.")

def func():
    time.sleep(1)  #
    print("This is what Xiaogang wrote.")

def red():
    time.sleep(2)  #
    print("This is Xiao Hong's function.")

start_time = time.time()  # time stamp
index()
print(time.time() - start_time)

start_time = time.time()  # time stamp
func()
print(time.time() - start_time)

start_time = time.time()  # time stamp
red()
print(time.time() - start_time)

(This method returns Greenwich Time, the number of seconds between 0:0 and 0 seconds on January 1, 1970. Also known as timestamp, it changes all the time.)

import time
print(time.time())

The above code is repetitive and tedious.

Improvement: (Write time in a function, which is function-oriented and reduces duplication of code)

import time

def index():
    time.sleep(2)  #
    print("This is Xiao Ming's function.")

def func():
    time.sleep(1)  #
    print("This is what Xiaogang wrote.")

def red():
    time.sleep(2)  #
    print("This is Xiao Hong's function.")

def times(func):
    start_time = time.time()  # time stamp
    func()
    print(time.time() - start_time)

times(index)
times(func)

Improvement:

First Edition Decorator
import time
def func():
    time.sleep(1)  #
    print("This is what Xiaogang wrote.")

def red():
    time.sleep(2)  #
    print("This is Xiao Hong's function.")

def index():
    time.sleep(2)  #
    print("This is Xiao Ming's function.")

def times(func):
    def foo():
        start_time = time.time()  # What the timestamp did before the decorated function was executed
        func()
        print(time.time() - start_time) #   What to do after the decorated function is executed
    return foo           # No parentheses

index = times(index)       # No parentheses
index()
func = times(func)
func()

(2) Grammatical Sugar (Python does one thing for us)

Write grammatical sugar at the top of the decorated function
def warpper(f):
    def inner():
        print("111")
        f()
        print("222")
    return inner

# One thing python did for us, grammatical sugar
@warpper  # func = warpper(func)
def func():
    print("Decorated function 1")

@warpper  # index = warpper(index)
def index():
    print("Decorated function 2")

func()
def warpper(f):
    def inner(*args,**kwargs):
        print("Before the decorated function is executed")
        ret = f(*args,**kwargs)
        print("After the decorated function is executed")
        return ret
    return inner

@warpper
def func(*args,**kwargs):
    print(f"Decorated{args,kwargs}")
    return "I am func function"

@warpper
def index(*args,**kwargs):
    print(11111)

print(func(1,2,3,4,5,6,7,8,a=1))

(3) Standard Edition Decorators:

def wrapper(func):
    def inner(*args,**kwargs):
        '''Executing operations before decorated functions'''
        ret = func()
        '''The operation after the decorated function is executed'''
        return ret
    return inner

This is the standard decorator, fully in line with the code open and closed principle.

4. Advancement of Decorators

(1) Decorator with ginseng

def auth(argv):
    def warpper(func):
        def inner(*args,**kwargs):
            if argv == "Blog Garden":
                print("Welcome to Blog Garden")
                user = input("user:")
                pwd = input("pwd:")
                if user == 'alex' and pwd == "dsb":
                    func(*args,**kwargs)
            elif argv == "Code cloud":
                print("Welcome to Logon Code Cloud")
                user = input("user:")
                pwd = input("pwd:")
                if user == 'alex' and pwd == "jsdsb":
                    func(*args, **kwargs)

        return inner
    return warpper

def foo():
    print("Decorated functions")

msg = input("Please enter the name of your login.:")
a = auth(msg)
foo = a(foo)
foo()
def auth(argv):
    def wrapper(func):
        def inner(*args,**kwargs):
            if argv:
                print("I added functionality.!")
                func(*args,**kwargs)
            else:
                func(*args,**kwargs)
        return inner
    return wrapper

https://www.cnblogs.com/

@auth(True)   # @ auth = foo = wrapper (foo) = auth (True) flask framework
def foo():
    print("It's a kindling.")
foo()

(2) Decorating a function with multiple ornaments

Decorate a function with more than one decorator. Execute the nearest decorator to the decorated function first.

def auth(func):             # inner in wrapper 1 decorator
    def inner(*args,**kwargs):
        print("An extra pot of meat was added.")
        func(*args,**kwargs)
        print("Meat in pot for 38 yuan")
    return inner

def wrapper1(func):        # inner in Warpper 2 Decorator
    def inner(*args,**kwargs):
        print("An additional stab was added.")
        func(*args,**kwargs)
        print("Thorns are eaten in vain")
    return inner

def wrapper2(func):         # Decorated function foo
    def inner(*args,**kwargs):
        print("Additional spicy pepper")
        func(*args,**kwargs)
        print("Hard to swallow")
    return inner
    
def foo(): 
    print("This is a Yuanbao Shrimp Hotel.")
    
foo = wrapper2(foo) # inner = wrapper2(foo)
foo = wrapper1(foo) # inner = wrapper1(inner)
foo = auth(foo)     # inner = auth(inner)
foo()               # inner() inside auth
def auth(func):            # inner in wrapper 1 decorator
    def inner(*args,**kwargs):
        print(123)
        func(*args,**kwargs)
        print(321)
    return inner


def wrapper1(func):         # inner in Warpper 2 Decorator
    def inner(*args,**kwargs):
        print(111)
        func(*args,**kwargs)
    return inner


def wrapper2(func):          # Decorated function foo
    def inner(*args,**kwargs):
        print(222)
        func(*args,**kwargs)
        print(567)
    return inner


@auth                 # 1           7
@wrapper1             #   2       6
@wrapper2             #    3    5
def foo():            #      4
    print("www.baidu.com")
foo()

Tags: Python

Posted on Fri, 06 Sep 2019 00:56:32 -0700 by Salis