@装饰器

实例一:

#encoding:utf-8

'''
装饰器在执行的时候,Func1函数作为参数传递给outer函数中的fun,
之后顺序执行wrapper函数,需要注意的是:在执行wrapper函数的时候,
相当于执行了Func1函数。
最后,返回wrapper函数给Func1函数。

'''

def outer(fun):
    def wrapper():
        print '顺序1'
        fun()
        print '顺序2'
    return wrapper

@outer
def Func1():
    print '执行函数'

Func1()

实例二:

import time

def deco(func):

    def wrapper():
        startTime = time.time()
        func()
        endTime = time.time()
        runTime = (endTime - startTime) * 1000
        print ("run time is %f ms" % runTime)
    return  wrapper

@deco
def myfunc():

    print ('myfunc startTime......')
    time.sleep(2)
    print ('myfunc endTime......')


print ("myfunc is :",myfunc.__name__)
# myfunc = deco(myfunc)
print ("myfunc is :",myfunc.__name__)
print ('\n')
myfunc()

猜你喜欢

转载自blog.csdn.net/kkkxiong1/article/details/81675692