• 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 "33[31m%s33[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')
  • 相关阅读:
    每周总结8.18
    每周总结7.28
    每周总结8.25
    每周总结7.21
    每周总结8.11
    每周总结8.4
    大道至简 读后感
    递归进行回文的判断
    课后作业1
    GoodBlogs Websites
  • 原文地址:https://www.cnblogs.com/xkops/p/6266070.html
Copyright © 2020-2023  润新知