Application Scenario and Example Usage of Python Decorator

  • 2021-11-01 03:52:58
  • OfStack

1. Description

Decoration is essentially an Python function that allows other functions to add additional functionality without any code changes. With the decoration, we can extract a lot of the same code that has nothing to do with the function function and continue to reuse it.

2. Application scenarios

Including log insertion, performance testing, transaction processing, caching, and permission verification.

3. Examples


#  Decorator 
# func Reference function 
def decorator(func):
    def wrapper(*args, **kwargs):
        #  Execute the internal logic of the function   Print time 
        print(time.time(), args, kwargs)
        #  Execute the logic in the calling function   Print different parameters 
        func(*args, **kwargs)
    return wrapper
# 1 Parameters 
@decorator
def function(param):
    print('function : this is decorator ' + param)
#  Two parameters 
@decorator
def function1(param1, param2):
    print('function1 : this is decorator ' + param1)
    print('function1 : this is decorator ' + param2)
# 3 Parameters (variable parameters) 
@decorator
def function2(param1, param2, **kwargs):
    print('function2 : this is decorator ' + param1)
    print('function2 : this is decorator ' + param2)
    print(kwargs)
function('param')
function1('param1' , 'param2')
function2('param1' , 'param2', x=1,y=2,z=3)

Content extension:

Function registry

Simple registry


funcs = []
def register(func):
  funcs.append(func)
  return func    
@register
def a():
  return 3
  
@register
def b():
  return 5  
#  Access results 
result = [func() for func in funcs]

Registry isolation (using different instances of classes)


class Registry(object):
  def __init__(self):
    self._funcs = []
  
  def register(self, func):
    self._funcs.append(func)
    
  def run_all(self):
    return [func() for func in self._funcs] 
r1 = Registry()
r2 = Registry()

@r1.register
def a():
  return 3
  
@r2.register
def b():
  return 5
  
@r1.register
@r2.register

Related articles: