Preface
One 、 How it was created
Two 、 Common scenarios
Preface1. Decorator is essentially a grammatical sugar , It is the function expansion of the decorated method or class , It is a facet oriented implementation method
2. Decorators can be divided into method decorators and class decorators , The difference between them is a decorator implemented with functions , One is a decorator implemented with classes , They can also decorate methods and classes
3. Class decorator looks more structured , So the following code implements the decorator All kinds of ornaments
1. establish “ Decoration method ” A kind of decorator
from functools import wraps# Decorator class class MyDecorator(object): def __init__(self, plusNum): self.plusNum = plusNum # Decorate with accessories def __call__(self, func): @wraps(func) # @wraps Ensure that the decorator does not change the original function structure of the decorated method def wrapped_function(*args, **kwargs): # Perform some operations before calling the decorated method --------------- # If not @wraps, The print result here will be funcName = func.__name__ print("funcName: {}".format(funcName)) # --------------------------------------- # Modify the input parameters of the decorated method -- num1 = args[0] + 2 num2 = args[1] + 3 args = (num1, num2) # ------------------- # Perform the decorated method ------------- res = func(*args, **kwargs) # ------------------------- # Perform some operations after calling the decorated method ------------- print("do something after the func...") # ------------------------------------- # Modify the output parameters of the decorated method -- res += self.plusNum # ------------------- # Return the parameters of the decorated method return res # Return to decorator method return wrapped_function# The way to be decorated @MyDecorator(3)def add(num1, num2): return num1+num2if __name__ == '__main__': # Overall execution process : # 1. Print add Method name # 2. Modify the decorated method into the reference # 3. Perform the decorated method # 4. Perform some operations after calling the decorated method # 5. Modify the output parameters of the decorated method # 6. Print the results print(add(5, 3)) # funcName: add # do something after the func... # 16
2. establish “ Methods in decoration class ” A kind of decorator
from functools import wraps# Decorator class class MyDecorator(object): def __init__(self, plusNum): self.plusNum = plusNum # Decorate with accessories def __call__(self, func): @wraps(func) # @wraps Ensure that the decorator does not change the original function structure of the decorated method def wrapped_function(*args, **kwargs): # The method here is the same as that of direct decoration # Perform some operations before calling the decorated method --------------- # If not @wraps, The print result here will be funcName = func.__name__ print("funcName: {}".format(funcName)) # --------------------------------------- # Notice here , If you need to modify the value of the input parameter , Then the index of parameters is from 1 Start not from 0 Start , Because the value of the first input parameter is the instance itself self # Modify the input parameters of the decorated method -- num1 = args[1] + 2 num2 = args[2] + 3 args = (args[0], num1, num2) # ------------------- # The method here is the same as that of direct decoration # Perform the decorated method ------------- res = func(*args, **kwargs) # ------------------------- # The method here is the same as that of direct decoration # Perform some operations after calling the decorated method ------------- print("do something after the func...") # ------------------------------------- # The method here is the same as that of direct decoration # Modify the output parameters of the decorated method -- res += self.plusNum # ------------------- # Return the parameters of the decorated method return res # Return to decorator method return wrapped_functionclass Operation(object): # Decorated class methods @MyDecorator(3) def add(self, num1, num2): return num1+num2if __name__ == '__main__': op = Operation() print(op.add(3, 5)) # funcName: add # do something after the func... # 16
3. establish “ Decoration ” A kind of decorator
from functools import wraps# Decorator class class MyDecorator(object): def __init__(self, plusNum): self.plusNum = plusNum # Decorate with accessories def __call__(self, Cls): @wraps(Cls) # @wraps Ensure that the decorator does not change the original structure of the decorated class def wrapped_function(*args, **kwargs): # Perform some operations before calling the decorated class --------------- # If not @wraps, The print result here will be clsName = Cls.__name__ print("clsName: {}".format(clsName)) # --------------------------------------- # Modify the input parameters of the decorated class --- num1 = args[0] + 2 num2 = args[1] + 3 args = (num1, num2) # ------------------- # Initialize the decorated class ------------- cls = Cls(*args, **kwargs) # ------------------------- # Perform some operations after initialization -------------------- print("do something after the func...") # ------------------------------------- # Add attributes and methods to class instances --------------------- cls.mul = 3 # Attribute added cls.plusNumber = self.plusNumber # Increase method # ------------------------------------------- # Return instance return cls # Return to decorator method return wrapped_function def plusNumber(self, num): return num + self.plusNum# The decorated class @MyDecorator(3)class Operation(object): def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def add(self): num3 = self.num1 + self.num2 num4 = self.plusNumber(num3*self.mul) # Properties and methods inserted using decorators return num4if __name__ == '__main__': # Overall execution process : # 1. Print Operation Class name # 2. Modify the initialization parameters of the class # 3. Initialization class # 4. Execute some methods after initialization # 5. Add mul Properties and plusNumber Method # 6. Instance execution add Function and call the new decoration function and decoration attribute # 7. Output results op = Operation(3, 5) print(op.add()) # clsName: Operation # do something after the func... # 42
Two 、 Common scenarios 1. Log
# todo
2. Performance testing
# todo
3. Loop execution
# todo
4. Interceptor
# todo
5. Data preprocessing ( Data cleaning )
# todo
6. Functional implant
# todo
This is about Python Decorator This is how to create decorators and common scenes , More about Python Decorator Please search the previous articles of SDN or continue to browse the relevant articles below. I hope you will support SDN more in the future !
Catalog introduction One 、 I