Python Learning Diary Decorator

1.import time

  a.time.time()

Gets the current time and returns a floating-point value

import time
print(time.time())  #1565422783.6497557

  b.time.sleep()

Let the program execute to this location and pause for a while

import time
start = time.time()
time.sleep(0.5)
print('hello world!')
end = time.time()
print(end - start)  #0.5000286102294922

 

2. decorator

Development Principle: Open and Closed Principle

The role of decorators: without changing the original function, add functions before and after the function

The essence of decorators: closure functions

 

When you want to know the execution time of a program

import time
start = time.time()
time.sleep(0.5)
print('hello world!')
end = time.time()
print(end - start)  #0.5000286102294922

Then pull out the function and turn it into a function.

import time
def func():
    time.sleep(0.5)
    print('hello world!')
def timer(func):
    start = time.time()
    func()
    end = time.time()
    print(end - start)
timer(func)     #hello world!
                #0.5000286102294922

Turn timer into a simple decorator

import time
def func():                 #Decorated functions
    time.sleep(0.5)
    print('hello world!')
def timer(func):            #Decoration function
    def inner():
        start = time.time()
        func()
        end = time.time()
        print(end - start)
    return inner            #Return inner Memory address of function
get_inner = timer(func)     #What the latter gets is inner The memory address is reassigned to get_inner
get_inner()                 #hello world!
                            #0.5000286102294922

Implementation steps:

Open and Closed Principle: Open means open to expansion, closed means closed to modification.

Grammatical sugar: @Decorator function name can replace the following

Decorator with parameter function

Decorate function decorators with multiple parameters

Summary: Decorator Template

import time
def wrapper(f):
    def inner(*args,**kwargs):
        #What to do before the decorated function
        res = f(*args,**kwargs)
        #What to do after the decorated function
        return res
    return inner
@wrapper
# func = wrapper(func)
def func():            #Decorated functions
    return
ret = func()
print(ret)

Tags: Python

Posted on Tue, 08 Oct 2019 13:32:55 -0700 by thefortrees