zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    《C++ Primer》学习笔记第2章 变量和基本类型
    Java学习笔记类的继承与多态特性
    Java的冒泡排序问题
    新起点,分享,进步
    MVC2中Area的路由注册实现
    了解一下new关键字实现阻断继承的原理
    利用Bing API开发的搜索工具(MVC+WCF)
    ASP.NET MVC中错误处理方式
    const和readonly内部区别
    WCF中校验参数的实现方式(一)
  • 原文地址:https://www.cnblogs.com/mess4u/p/3851358.html
Copyright © 2011-2022 走看看