• Python 修饰器


    描述:对于函数foo,使用修饰器修饰,在执行foo函数的同时统计执行时间。这样其他函数都可以使用此修饰器得到运行时间。

    (有返回值和没有返回值的函数要用不同的修饰器似乎)

    (对于有返回值的函数,不确定用result存储实际函数执行结果再最终返回的方法是不是恰当)

     1 import time
     2 
     3 def timeit(func):
     4 
     5     def wrapper(word):
     6         start = time.clock()
     7         result = func(word)
     8         end = time.clock()
     9         print 'Used: ', end - start
    10         return result
    11 
    12     return wrapper
    13 
    14 @timeit
    15 def foo(word):
    16     return word
    17 
    18 
    19 print foo("123")
     1 def transfer(func):
     2     def wrapper():
     3         result = func()
     4 
     5         result_new = {}
     6         for key in result:
     7             result_new[key] = result[key]
     8             if type(result_new[key]) is type("H"):
     9                 result_new[key] = result_new[key].upper()
    10 
    11         return result_new
    12 
    13     return wrapper
    14 
    15 @transfer
    16 def foo():
    17     result = {}
    18     result['name'] = "wang"
    19     result['age'] = 1
    20 
    21     return result
    22 
    23 print foo()

     在类里

     1 class test:
     2     def __init__(self):
     3         pass
     4 
     5     def transfer(func):
     6         def wrapper(instance):
     7             result = func(instance)
     8             result_new = {}
     9             for key in result:
    10                 result_new[key] = result[key].upper()
    11 
    12             return result_new
    13 
    14         return wrapper
    15 
    16     @transfer
    17     def getDict(self):
    18         result = {}
    19         result["name"] = "wang"
    20         return result
    21 
    22 t = test()
    23 print t.getDict()
    24 class test:
    25     def __init__(self):
    26         pass
    27 
    28     def transfer(func):
    29         def wrapper(instance):
    30             result = func(instance)
    31             result_new = {}
    32             for key in result:
    33                 result_new[key] = result[key].upper()
    34 
    35             return result_new
    36 
    37         return wrapper
    38 
    39     @transfer
    40     def getDict(self):
    41         result = {}
    42         result["name"] = "wang"
    43         return result
    44 
    45 t = test()
    46 print t.getDict()

     

    参考文章:

    http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

  • 相关阅读:
    AsyncTask 处理耗时操作&&显示进度条
    AutoCompleteTextView 自定义提示样式
    Android:Error:Execution failed for task ':app:clean'. > Unable to delete directory
    MaterialRefreshLayout+ListView 下拉刷新 上拉加载
    element table 表格 修改背景为透明并去除边框
    vue-element-admin 多层路由问题
    SQLServer 语句相关
    润乾报表
    v-charts
    sql 循环 ,随机数,循环插入一年数据
  • 原文地址:https://www.cnblogs.com/mess4u/p/3851358.html
Copyright © 2020-2023  润新知