美文网首页
Python函数修饰器

Python函数修饰器

作者: louyang | 来源:发表于2019-01-27 17:35 被阅读6次

    假设我们写一个小函数,打印当前的时间和一个随机整数,代码如下:

    import datetime
    import random
    
    def print_random(min,max):
        print("{} : {}".format(datetime.datetime.now().time(), random.randint(min,max)))
    
    print_random(1, 10)
    

    运行的结果是:

    16:18:41.915328 : 7
    

    假设,我们想周期性的打印随机数,而且不改变print_random函数的参数,我们可以使用函数修饰器,代码如下:

    import datetime
    import random
    import time
    
    def timeout(duration, interval):
        def decorated(func):
            def wraper(*para):
                mydur = duration
                myint = interval
                running_time = 0
                while running_time < duration:
                    func(*para)
                    time.sleep(myint)
                    running_time += myint
            return wraper
        return decorated
    
    @timeout(10, 1)
    def print_random(min,max):
        print("{} : {}".format(datetime.datetime.now().time(), random.randint(min,max)))
    
    print_random(1, 10)
    

    运行结果:

    17:16:37.008791 : 4
    17:16:38.010875 : 3
    17:16:39.013730 : 4
    17:16:40.016595 : 9
    17:16:41.018707 : 3
    17:16:42.020730 : 8
    17:16:43.022751 : 5
    17:16:44.024706 : 1
    17:16:45.026640 : 3
    17:16:46.028182 : 4
    

    相关文章

      网友评论

          本文标题:Python函数修饰器

          本文链接:https://www.haomeiwen.com/subject/zkxnjqtx.html