Python装饰器示例

目标:

  1.编写运行函数,生成10个数的列表,没生成一个睡眠一会

  2.编写装饰器,完成函数耗时计算

 

1.编写生成10个数的列表,并睡眠0.2s

代码如下:

[root@localhost python]# cat deco1.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time

def loop():
    result = []
    for i in xrange(10):
        result.append(i)
        time.sleep(0.2)
    return result

if __name__ == "__main__":
    print loop()

 

2.编写装饰器,实现计算loop()函数,生成10个数列表的耗时

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
#装饰器部分
def deco(func): def timeit(): start = time.time() result = func() end = time.time() return (result, end - start) return timeit
#引用装饰器 @deco
def loop(): result = [] for i in xrange(10): result.append(i) time.sleep(0.2) return result if __name__ == "__main__": print loop()

•运行代码,测试效果

[root@localhost python]# python deco1.py
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 2.0052788257598877)

 

*提示:如果有多个函数,可以直接使用装饰器即可,如以下多个函数情况:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time

def deco(func):
    def timeit():
        start = time.time()
        result = func()
        end = time.time()
        return (result, end - start)
    return timeit



@deco
def loop():
    result = []
    for i in xrange(10):
        result.append(i)
        time.sleep(0.5)
    return result

@deco
def test():
    t1 = []
    for i in xrange(10):
        t1.append(i)
        time.sleep(0.8)
    return t1


if __name__ == "__main__":
    print loop()
    print test()

 

 

附录:

装饰器,实现多个函数字体的统一设置

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def set_color(func):
    def color(*args):
        return "\033[31m%s\033[0m" % func(*args)
    return color

@set_color
def hello():
    return "hello,world!"

@set_color
def greet():
    return "How are you?"

@set_color
def welcome(word):
    return "Welcome to %s" % word

if __name__ == '__main__':
    print hello()
    print greet()
    print welcome('bj')

 

posted @ 2017-01-09 17:42  韩德田  阅读(274)  评论(0编辑  收藏  举报