SoFunction
Updated on 2024-11-16

The role of decorator in python explained in detail

1. Concepts

Decorator (decorator) is: define a function, want to dynamically increase the function at runtime, but do not want to change the function itself. Can play the function of reuse code, to avoid the repetition of each function to write code, in short, is to expand the function of the original function of a function. In python, decorator is divided into function decorator and class decorator. python built-in @ language is to simplify the decorator call.

List a few decorator functions:

Print log: @log

Detection performance: @performance

Database transaction: @transaction

URL routing: @post('/register')

2. Usage

(1) No parameter decorator

Write a @performance which prints out the time of a function call.

import time

def performance(f):
 def log_time(x):
  t1 = ()
  res = f(x)
  t2 = ()
  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)

Run results:

call factorial() in 0.006009s 2 3628800

Principles of Operation:

At this point, factorial is passed as a function object of performance to f. When factorial(10) is called it is also a call to the log_time(10) function, and inside the log_time function, f is called, which creates the effect of a decorator. Show that f is the decorated function and x is an argument to the decorated function.

(2) Decorator with parameters

Please 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 = ()
   r = f(*args, **kw)
   t2 = ()
   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)

Run results:

call factorial() in 9.381056 ms 2 3628800

Principles of Operation:

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

Here performance('ms') returns the perf_decorator function object, performance('ms')(factor) is actually perf_decorator(factor), and then the rest is the same as above.

This is the whole content of this article, I hope it will help you to learn more.