Python裝飾器示例

目標:python

  1.編寫運行函數,生成10個數的列表,沒生成一個睡眠一會app

  2.編寫裝飾器,完成函數耗時計算函數

 

1.編寫生成10個數的列表,並睡眠0.2soop

代碼以下:測試

[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個數列表的耗時spa

代碼以下:code

#!/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()

•運行代碼,測試效果blog

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

 

*提示:若是有多個函數,能夠直接使用裝飾器便可,如如下多個函數狀況:utf-8

#!/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')
相關文章
相關標籤/搜索