zoukankan      html  css  js  c++  java
  • python-装饰器案例1

    python-装饰器案例1

    高阶函数+嵌套函数=装饰器

    例1:

    import time
    def timer(func):
        def deco():
            start_time=time.time()
            func()
            stop_time=time.time()
            print("kezi the %s"%(stop_time-start_time))
        return deco
    @timer
    def test1():
        time.sleep(3)
        print ("in the test1")
    @timer
    def test2():
        time.sleep(3)
        print("in the test2")
    
    #test1=timer(test1)=@timer
    test1()
    
    #test2=timer(test2)=@timer
    test2()
    
    
    打印结果
    in the test1
    kezi the 3.0000288486480713
    in the test2
    kezi the 3.0009706020355225

    例2  代参数的装饰

    import time
    def timer(func):
        def deco(*arg1,**age2):
            start_time=time.time()
            func(*arg1,**age2)
            stop_time=time.time()
            print("kezi the %s"%(stop_time-start_time))
        return deco
    @timer
    def test1():
        time.sleep(3)
        print ("in the test1")
    @timer
    def test2():
        time.sleep(3)
        print("in the test2")
    @timer
    def test3(name,age):
        time.sleep(3)
        print("in the test3:",name,age)
    
    # #test1=timer(test1)=@timer
    test1()
    #
    # #test2=timer(test2)=@timer
    test2()
    test3("kezi",33)
    
    打印结果
    in the test1
    kezi the 3.00183367729187
    in the test2
    kezi the 3.0006985664367676
    in the test3: kezi 33
    kezi the 3.000452756881714
  • 相关阅读:
    去掉苹果设备中按钮的默认样式
    用纯css写三角形
    行内元素中间出现空隙
    控制字间距
    单选按钮只能选中一个
    ie6出现双倍边距的问题
    17-比赛1 B
    ACM模板
    STL 入门 (17 暑假集训第一周)
    UVA 1594 Ducci Sequence(紫书习题5-2 简单模拟题)
  • 原文地址:https://www.cnblogs.com/kezi/p/12004322.html
Copyright © 2011-2022 走看看