• Decorator


     1 装饰器 Decorator,
     2 
     3     先来看看对 decorator 这个名词的解释,
     4         一个可调用的对象 A (decorator), 返回另一个可调用的对象 B, 在可调用的对象 C 的定义体之前通过语法 @A 调用.
     5         Python 的解释器会调用 A(C), 把 C 的定义提替换成 B 并返回(return).
     6         如果可调用对象 C 是函数, 那么将 A 称作 '函数装饰器(function decorator)'; 若 C 是类,则称 A 为 '类装饰器(class decorator)'.
     7         decorator 的作用是对目标对象 C 进行'加工处理'(可以理解为对对象 C '','','',''等), 并返回处理处理后的新对象.
     8 
     9     通过例子说明,
    10         装饰器 decorator 是可以调用的对象, 其参数是另一个被装饰对象 object (class or function).
    11         装饰器 可能会'加工'被装饰的对象, 然后把它返回, 又或者将其替换成另一个可以调用对象返回.
    12 
    13         函数装饰器例子(function decorator),
    14             def A(a,b):
    15                 print(a+b)
    16             函数 A 直接打印 两个入参的和, 现在有这样一个需求,再打印结果(和)之前, 提示:'Start calculating the sum of a and b ...',
    17             来看看这个需求如何通过 decorator 来实现.
    18                 def C(A):                                                        #1 传入 被调用对象
    19                     def innerC(a,b):                                             #2 加工函数, 对被装饰对象 A 进行加工处理, 参数与目标对象 A 保持一直
    20                         print('Start calculating the sum of %d and %d' % (a,b))  #3  '需求' 的实现
    21                         return A(a,b)                                            #4 将被装饰函数的调用返回,保证'闭环', 返回的是 对象 A 的 return 的对象(非必选的 return)
    22                     return innerC                                                #5 将包装对象 A 的 函数返回(必选的return, 保证对对象 A 装饰后得到新对象是可调用的)
    23 
    24                 @C                                                               #6 装饰器语法
    25                 def A(a,b):
    26                     print(a + b)
    27 
    28                 A(1,3)
    29 
    30                 Output,
    31                     Start calculating the sum of 1 and 3 ...   #3
    32                     4
    33 
    34         类装饰器例子(class decorator),
    35             同样地, 计算 a, b 的和, 用类来实现, 并将 decorator C 应用到这个类上, 看看输出结果如何,
    36                 @C
    37                 class A(object):
    38                     def __init__(self,a,b):
    39                         print(a + b)
    40 
    41                 Output,
    42                     Start calculating the sum of 3 and 5 ...
    43                     8
    44                     <__main__.A object at 0x038234D0>
    45                     # 同样, 通过 class decorator C 满足了在计算之前打印提示:'Start calculating the sum of a and b ...' 的需求.
    46 
    47 
    48         注, 装饰器的一个关键特性是, 它们在被装饰的函数定义之后立即运行。通常是在导入时。
    49             实际的情况是, 更多的时候装饰器函数通常在一个模块中被定义, 然后被应用到其他模块儿中的对象上.
  • 相关阅读:
    Session cookie 原理
    asp.net core service mesh
    js 常用库
    asp.net core consul
    asp.net core polly
    asp.net core ocelot
    第十五章 享元模式 Flyweight
    第十四章 策略模式 Strategy
    mysql 主从复制
    mysql 执行计划
  • 原文地址:https://www.cnblogs.com/zzyzz/p/7526290.html
Copyright © 2020-2023  润新知