首页 > 编程语言 > 详细

python之装饰器 实例

时间:2016-12-29 08:37:43      阅读:143      评论:0      收藏:0      [点我收藏+]
=====================================写法1==========================
import time
def timer(func):
    def deco():
        start_time = time.time()
        func()
        stop_time = time.time()
        print(‘the func run time is %s‘ %(stop_time - start_time
    return deco
def test1():
    print(‘this is test1‘)
def test2():
    print(‘this is test2‘)
test1 = timer(test1)  把deco内在地址赋值给test1
test1()  #test1未被改变,而且调用方式也未被改变

=====================================写法2==========================

import time
def timer(func):
    def deco():
        start_time = time.time()
        func()
        stop_time = time.time()
        print(‘the func run time is %s‘ %(stop_time - start_time
    return deco
####想要哪个函数调用装饰器就在哪个头部加这个内容
####@timer    ==  test1 = timer(test1) 
@timer 
def test1():
    print(‘this is test1‘)
def test2():
    print(‘this is test2‘)
test1()  #test1未被改变,而且调用方式也未被改变

=====================================修改写法2==========================

import time
def timer(func):
    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        stop_time = time.time()
        print(‘the func run time is %s‘ %(stop_time - start_time
    return deco
####想要哪个函数调用装饰器就在哪个头部加这个内容
####@timer    ==  test1 = timer(test1) 
@timer 
def test1():
    time.sleep(3)
    print(‘this is test1‘)
def test2(name,age):
    time.sleep(3)
    print(‘this is test2‘)
    print(‘name:%s,age:%s‘ %(name,age))
test1()  #test1未被改变,而且调用方式也未被改变
test2(‘大盗林工‘,18)


python之装饰器 实例

原文:http://daring.blog.51cto.com/891785/1887092

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