• 装饰器知识汇总


      1 第一种;未使用@符号
      2 def a_new_decorator(a_func): # a_func = a_function_requiring_decoration
      3     def wrapTheFunction():
      4         """the doc for wrapTheFunction"""
      5         print("I am doing some boring work before executing a_func()")
      6         a_func() # a_function_requiring_decoration()
      7         print("I am doing some boring work after executing a_func()")
      8 
      9     return wrapTheFunction
     10 
     11 def a_function_requiring_decoration():
     12     """Hey you! Decorate me!"""
     13     print("I am the function which needs some decoration to remove my foul smell")
     14 
     15 a_function_requiring_decoration()
     16 # I am the function which needs some decoration to remove my foul smell
     17 a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) #注意这种写法,相当于是执行函数后并返回一个函数,然后把返回的函数赋值给一个变量
     18 a_function_requiring_decoration()
     19 # I am doing some boring work before executing a_func()
     20 # I am the function which needs some decoration to remove my foul smell
     21 # I am doing some boring work after executing a_func()
     22 
     23 第二种,使用@符号
     24 def a_new_decorator(a_func): # a_func = a_function_requiring_decoration
     25     def wrapTheFunction():
     26         """the doc for wrapTheFunction"""
     27         print("I am doing some boring work before executing a_func()")
     28         a_func() # a_function_requiring_decoration()
     29         print("I am doing some boring work after executing a_func()")
     30 
     31     return wrapTheFunction
     32 
     33 # a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
     34 @a_new_decorator  # @这句这个等价于上面的那句
     35 def a_function_requiring_decoration():
     36     """Hey you! Decorate me!"""
     37     print("I am the function which needs some decoration to remove my foul smell")
     38 
     39 a_function_requiring_decoration()
     40 # I am doing some boring work before executing a_func()
     41 # I am the function which needs some decoration to remove my foul smell
     42 # I am doing some boring work after executing a_func()
     43 
     44 第三种:获取原来函数的信息等
     45 from functools import wraps
     46 
     47 def a_new_decorator(a_func): # a_func = a_function_requiring_decoration
     48     @wraps(a_func) #注意这个的写法
     49     def wrapTheFunction():
     50         """the doc for wrapTheFunction"""
     51         print("I am doing some boring work before executing a_func()")
     52         a_func() # a_function_requiring_decoration()
     53         print("I am doing some boring work after executing a_func()")
     54 
     55     return wrapTheFunction
     56 
     57 @a_new_decorator # a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
     58 def a_function_requiring_decoration():
     59     """Hey you! Decorate me!"""
     60     print("I am the function which needs some decoration to remove my foul smell")
     61 
     62 a_function_requiring_decoration()
     63 
     64 print(a_function_requiring_decoration.__name__) # a_function_requiring_decoration
     65 
     66 若不加上@wraps(a_func),执行print(a_function_requiring_decoration.__name__),返回的结果是wrapTheFunction
     67 
     68 第四种:传参
     69 from functools import wraps
     70 def logit(logfile='out.log'): # 外面又多了一层函数
     71     def loggint_decorator(func):
     72         @wraps(func) # 注意这个的位置
     73         def wrapped_function(*args,**kwargs):
     74             log_string = func.__name__ + "was called"
     75             print(log_string)
     76             with open(logfile,'a') as opened_file:
     77                 opened_file.write(log_string+'
    ')
     78             return func(*args,**kwargs)
     79         return wrapped_function
     80     return loggint_decorator
     81 
     82 @logit() # 注意后面加上的有括号,需要传参时才加上括号,并且在外面又套了一个函数,未指定参数使用默认值,
     83 def myfunc1():
     84     print('myfunc1')
     85 
     86 # myfunc1()
     87 
     88 @logit(logfile='func2.log') # 指定参数
     89 def myfunc2():
     90     print('myfunc2')
     91 
     92 myfunc2()
     93 
     94 
     95 第五种:装饰器类
     96 from functools import wraps
     97 
     98 class logit(): # 没有object,说明是py3类的写法
     99 
    100     def __init__(self,logfile='out.log'):
    101         self.logfile = logfile
    102 
    103     def __call__(self, func): # 注意这个的写法
    104         @wraps(func)
    105         def wrapped_function(*args,**kwargs):
    106             log_string = func.__name__ + " was called!"
    107             print(log_string)
    108             with open(self.logfile,'a') as opened_file:
    109                 opened_file.write(log_string+"
    ")
    110             self.notify()
    111             return func(*args,**kwargs)
    112         return wrapped_function
    113 
    114     def notify(self):
    115         print('notify')
    116 
    117 @logit()
    118 def myfunc1():
    119     print('myfunc1')
    120 
    121 myfunc1()
    122 
    123 第六种:装饰器子类
    124 from functools import wraps
    125 
    126 class logit():
    127 
    128     def __init__(self,logfile='out.log'):
    129         self.logfile = logfile
    130 
    131     def __call__(self, func):
    132         @wraps(func)
    133         def wrapped_function(*args,**kwargs):
    134             log_string = func.__name__ + " was called!"
    135             print(log_string)
    136             with open(self.logfile,'a') as opened_file:
    137                 opened_file.write(log_string+"
    ")
    138             self.notify()
    139             return func(*args,**kwargs)
    140         return wrapped_function
    141 
    142     def notify(self):
    143         print('notify')
    144 
    145 @logit()
    146 def myfunc1():
    147     print('myfunc1')
    148 
    149 # myfunc1()
    150 
    151 class email_logit(logit):
    152     '''
    153     一个logit的实现版本,可以在函数调用时发送email给管理员
    154     '''
    155     def __init__(self,email="admin@myproject.com",*args,**kwargs):
    156         self.email = email
    157         super().__init__(*args,**kwargs) #py3子类继承父类的写法
    158 
    159     def notify(self):
    160         print('发送邮件')
    161 
    162 @email_logit()
    163 def myfunc2():
    164     print('myfunc2')
    165 
    166 myfunc2()
  • 相关阅读:
    UEBA——通过用户画像识别安全威胁
    《国富论》西方经济学的“圣经”——自利的人性是资本主义市场经济的基本假设,财富的源泉是劳动,钱变成可再生的钱“资产”而不是负债
    python berkeley 操作——尤其提示 需版本匹配
    druid.io 海量实时OLAP数据仓库 (翻译+总结) (1)——分析框架如hive或者redshift(MPPDB)、ES等
    万亿级日志与行为数据存储查询技术剖析(续)——Tindex是改造的lucene和druid
    编译原理Tiny语言的定义
    ubuntu 安装python,easy_install和pip
    ubuntu 安装eclipse
    ubuntu rpm 包安装使用
    linux chmod权限
  • 原文地址:https://www.cnblogs.com/sanduzxcvbnm/p/9456462.html
Copyright © 2020-2023  润新知