装饰器的解析

# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 10:06:28 2019

@author: wangzhe
   装饰器的用法  2019-03-27
"""

import time
import functools

x = 1
y = x
#(1)
def test0():
    time.sleep(2)
    print("test is run")

def test1():
    print("Do Something")

print("test1函数的地址:" + str(test1))
print("test1函数的内容:" + str(test1()))
#test2 = lambda x:x * 2
#print(test2(x))

#(2)
def doce(func):
    start = time.time()
    func()
    end = time.time()
    print("函数执行的时间为:" + str(end-start))

#将函数名当作实参传给另外一个函数(“实参高阶函数”)
#返回值中包含函数名(“返回值高阶函数”)
#doce(test)

#(3) 
def doce1(func):
    print("不修改函数test的调用方式test()")
    return func
#t = doce1(test)
#t()

#(4)
def timer(func):
    #为了防止test的函数名改变,采用如下方法(1)
    @functools.wraps(func)
    def doce(*args,**kwargs):
        start = time.time()
        res = func(*args,**kwargs)
        end = time.time()
        print("函数执行的时间为:" + str(end-start))
        #为了防止test的函数名改变,采用如下方法(2)
        #doce.__name__ = func.__name__
        return res
    return doce  #返回doce()函数的地址

#test = timer(test)  #等价于@timer
#test()  #此时的test不是原来的test了,而是doce
@timer
def test(s):
    time.sleep(2)
    print("test is run")
    return "你好!!"

print(test("123"))
print("test函数名是:" + str(test.__name__))



猜你喜欢

转载自blog.csdn.net/weixin_42631192/article/details/88839115