zoukankan      html  css  js  c++  java
  • python学习杂记--装饰器

    装饰器可以用来在不改变原函数的基础上,为原函数增添功能

    示例如下:

     1 import time
     2 
     3 def decorator1(function):
     4     def wrapper(*args,**kwargs):
     5         function(*args,**kwargs)
     6         print("------------ running function : %s  --------------"%function.__name__)
     7     return wrapper
     8 
     9 def decorator2(function):
    10     def wrapper(*args,**kwargs):
    11         starttime = time.time()
    12         function(*args,**kwargs)
    13         endtime = time.time()
    14         total_time = (endtime - starttime)
    15         print("------------ the function spend time is %s --------------"%total_time)
    16     return wrapper
    17 
    18 @decorator1
    19 @decorator2
    20 def func_test1(arg1,arg2):
    21     print("hello")
    22     time.sleep(2)
    23     print("world")
    24     print("arg1 is %s , arg2 is %s"%(arg1,arg2))
    25 
    26 @decorator2
    27 def func_test2(arg1,arg2,arg3):
    28     print("hello")
    29     time.sleep(2)
    30     print("world")
    31     print("arg1 is %s , arg2 is %s , arg3 is %s" % (arg1, arg2,arg3))
    32 
    33 
    34 
    35 if __name__ == '__main__':
    36     func_test1("A","B")
    37     func_test2("C","D","E")

    对应输出结果为:

    1 hello
    2 world
    3 arg1 is A , arg2 is B
    4 ------------ the function spend time is 2.000811815261841 --------------
    5 ------------ running function : wrapper  --------------
    6 hello
    7 world
    8 arg1 is C , arg2 is D , arg3 is E
    9 ------------ the function spend time is 2.000079393386841 --------------

    这个例子要注意的是3点

    1.定义装饰器的语法:

    如果要装饰的函数是不包含参数的,那么:例如decorator1的function就不需要参数了,加上*args,**kwargs就可以覆盖到function函数中存在任意个参数的情况了

    2.定义装饰器时,return返回的值是wrapper,不是wrapper()

    3.多个装饰器装饰同一个函数时,执行的顺序是按照从上到下的顺序依次执行的

  • 相关阅读:
    MVP 实战
    Model 层
    Presenter 层
    View 层
    DB数据库的基本操作
    MongoDB数据库基本操作
    转换函数
    字符串函数
    空值处理
    Java中使用Redis的几种数据类型总结
  • 原文地址:https://www.cnblogs.com/RuiRuia/p/13913849.html
Copyright © 2011-2022 走看看