• python 装饰器


    python 装饰器Decorator

    #在不改变函数代码的情况下,添加功能

    import time

    def timeDecorator(func):
    def getTime(args):
    t0 = time.time()
    re = func(args)
    print re
    print "执行%s耗时%fs"%((func.func_name),(time.time() - t0))
    #print func.func_name
    return getTime
    @timeDecorator
    def getEven(args):
    args = int(args)
    i = 1
    while i <= args:
    print 2 * i
    i += 1
    return 'aaa'
    getEven(100000)

    执行结果:

    2
    4
    6
    ......
    200

    aaa
    执行getEven耗时0.001000s

    #多参数装饰器(变量为函数)

    def func2(a, b):
    print 'func2'
    def func3(c, d):
    print 'func3'
    def Decorator(before_func,after_func ):
    def outer(main_func):
    def wrapper(args, args2):
    before_result = before_func(args, args2)
    if before_result == None:
    print 'before_func'
    main = main_func(args, args2)
    if main == None:
    print 'main_func'
    after_result = after_func(args, args2)
    if after_result == None:
    print 'after_func'
    return wrapper

    return outer


    @Decorator(func2, func3)
    def func1(args, args2):
    print 'func1'
    return 1
    if __name__ == '__main__':
    func1(0,0)

    输出:

    func2
    before_func
    func1
    func3
    after_func

  • 相关阅读:
    2016四川省赛 Floyd-Warshall
    CF374 Maxim and Array
    CF374 Journey
    hdu5730 Shell Necklace
    hihocoder1388 Periodic Signal
    hihocoder1391 Country
    hdu 5903 Square Distance
    hdu5904 LCIS
    Python学习-2.安装IDE
    Python学习-1.安装Python
  • 原文地址:https://www.cnblogs.com/3one/p/5547761.html
Copyright © 2020-2023  润新知