Definition: An adorner is essentially a function that is used to decorate other functions (that is, adding additional functionality to other functions):
- Cannot modify the source code of the decorated function
- Cannot modify the calling method of the decorated function
Decorator Preparation Knowledge:
- Function name is "variable"
- Higher order functions
- Pass a function name as an argument to another function (add a function to it without modifying the source code of the decorated function)
- The return value contains the function name (does not modify the function's Calling method)
- Nested functions
- Higher order function + nested function = = Adorner
Example:
#!usr/bin/env python#-*-coding:utf-8-*-import timedef Deco (func): Def wrapper (*args,**kwargs): #*args,**kwargs Can implement MyFunc outgoing arbitrary parameters start_time = Time.time () res = func (*args,**kwargs) end_time = Time.time () pr Int ("Elapsed time%s"% (end_time-start_time)) return res #如果func有返回值那么将其返回 return wrapper @deco #等价于 MYF UNC = Deco (MYFUNC) If you want to think about other parameters in the adorner, you can pass in the parameters such as deco ("xxx") after Deco, and the adorner will add a function nesting, and the parameters passed through Deco should be at the outermost layer, decorator ("XXX" ) def myfunc (): Time.sleep (3) print ("in MyFunc") MyFunc ()
Python Road-Decorators