首页 > 编程语言 > 详细

Python - 装饰器

时间:2017-12-03 21:27:50      阅读:238      评论:0      收藏:0      [点我收藏+]
import time
import functools

def exec_time(func):
    def wrapper(*args, **kw):
        print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time())))
        return func(*args, **kw)
    return wrapper

@exec_time
def testfunc():
    print("test function...")

testfunc()
print(testfunc.__name__)

print("=====================")

def exec_time(text):
    def deractor(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print(time.strftime(text, time.localtime(time.time())))
            return func(*args, **kw)
        return wrapper
    return deractor

@exec_time(‘%Y-%m-%d‘)
def testfunc():
    print("test function...")

testfunc()
print(testfunc.__name__)

print("=====================")

def exec_time(text):
    def deractor(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print("begin time:", time.strftime(text, time.localtime(time.time())))
            t = func(*args, **kw)
            print("end time:", time.strftime(text, time.localtime(time.time())))
            return t;
        return wrapper
    return deractor

@exec_time(‘%Y-%m-%d %H:%M:%S‘)
def testfunc():
    print("test function...")

testfunc()
print(testfunc.__name__)

 

output:

2017-12-03 20:50:00
test function...
wrapper
=====================
2017-12-03
test function...
testfunc
=====================
begin time: 2017-12-03 20:50:00
test function...
end time: 2017-12-03 20:50:00
testfunc

 

Python - 装饰器

原文:http://www.cnblogs.com/hfultrastrong/p/7967214.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!