python decorator 装饰器

python装饰器是个对嵌套函数的语法糖
作用是在函数调用方法不变的情况下,将函数包装成另一个函数来使用

import time
def sum1():
    sum = 1 + 2
    print (sum)
def timeit(func):
    def test():
        start = time.clock()
        func()
        end = time.clock()
        print func.__name__, ": time used:", end - start
    return test
sum1 = timeit(sum1)
sum1()
@timeit
def func2():
    print "hello"
func2()
def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped
def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped
@makebold
@makeitalic
def hello():
    return "hello world"
print hello()  ## returns "<b><i>hello world</i></b>"

输出

3
sum1 : time used: 2.05264400285e-05
hello
func2 : time used: 1.500009079e-05
<b><i>hello world</i></b>

参考: http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python

原文地址:https://www.cnblogs.com/iois/p/6358112.html