zoukankan      html  css  js  c++  java
  • 关于语法糖参数的实现

    首先关于装饰器

    1。装饰器的功能实现

    import time
    def timmer(func):
    def wrapper():
    start_time=time.time()
    res = func()
    stop_time=time.time()
    print('程序运行时间%s'%(stop_time-start_time))
         return res
    return wrapper

    @timmer#test=timmer(test)
    def test():
    time.sleep(3)
    print('test函数运行完毕')

    test()

    以上是最简单的装饰器,实现了函数参数返回值的装饰

    增加一个装饰功能(计算运行时间)

    2。如何在语法糖传参实现装饰器的附加功能

    import time


    def timer():
    return time.time()


    def space_outer(x,*y):
    def outer(func):
    def inner(*args, **kwargs):
    start_time = x()
    res = func(*args, **kwargs)
    stop_time = x()
    print('%s程序运行时间%s' % (y,(stop_time - start_time)))
    return res

    return inner

    return outer


    @space_outer(timer,'china','shanghai')
    def test():
    time.sleep(3)
    print('test函数运行完毕')

    可以发现,我在语法糖上增加一个参数,使得整个装饰功能得到增强,同样是测试运行时间,新的功能运行更加清晰明了,且可以举一反三

  • 相关阅读:
    Linq&Lumbda
    PS颜色模式
    WPF绑定方式
    明三杰刘健
    齐有鲍叔,郑有子皮
    朱厚照
    管子&小白
    时间
    人外有人之神箭手养繇基篇
    楚共王
  • 原文地址:https://www.cnblogs.com/vincent-sh/p/13058568.html
Copyright © 2011-2022 走看看