Details of the role of decorator in python

  • 2020-11-18 06:22:24
  • OfStack

1, concept,

A decorator (decorator) defines a function that wants to add functionality dynamically at run time without changing the code of the function itself. Can play the function of reuse code, avoid each function repetitive code writing, in short, is to expand the original function function of 1 function. In python, decorators (decorator) are divided into function decorators and class decorators. The @ language built into python is designed to simplify decorator calls.

List several decorator functions:

Print log: @log

Detection performance: @performance

Database transaction: @transaction

URL route: @ES21en ('/register')

2. Usage

(1) No parameter decorator

Write 1 @performance that prints out the time of the function call.


import time

def performance(f):
 def log_time(x):
  t1 = time.time()
  res = f(x)
  t2 = time.time()
  print 'call %s() in %fs' %(f.__name__,(t2 - t1))
  return res
 return log_time

@performance
def factorial(n):
 return reduce(lambda x,y : x*y,range(1,n+1))

print factorial(10)

Operation results:

[

call factorial() in 0.006009s 2 3628800

]

Operating principle:

At this point, factorial is passed to f as a function object of performance. When factorial(10) is called, the log_time(10) function is called, and inside the log_time function, f is called, resulting in the effect of the decorator. Indicates that f is the decorated function and x is the parameter of the decorated function.

(2) With parameter decorator

Add a parameter to @performace to allow 's' or 'ms' to be passed in.


import time

def performance(unit):
 def perf_decorator(f):
  def wrapper(*args, **kw):
   t1 = time.time()
   r = f(*args, **kw)
   t2 = time.time()
   t = (t2 - t1)*1000 if unit =='ms' else (t2 - t1)
   print 'call %s() in %f %s'%(f.__name__, t, unit)
   return r
  return wrapper
 return perf_decorator

@performance('ms') 
def factorial(n):
 return reduce(lambda x,y: x*y, range(1, n+1))

print factorial(10)

Operation results:

[

call factorial() in 9.381056 ms 2 3628800

]

Operating principle:

Its internal logic is factorial=performance('ms')(factorial);

performance('ms') returns perf_decorator function object, performance('ms')(factorial) is perf_decorator(factorial), and the rest is the same as above.


Related articles: