zoukankan      html  css  js  c++  java
  • python 装饰器详解

    装饰器:

    定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能

    原则:1.不能修改被装饰的函数的源代码

       2.不能修改被装饰的函数的调用方式

    import time

    #嵌套函数
    def foo():
    print('in the foo')
    def bar():
    print('in the bar')
    bar()
    foo()


    #装饰器
    def timer(func):
    def deco(*args,**kwargs):#timer(test) func=test *args,**kwargs带人参数

    start_time = time.time()
    func(*args,**kwargs)#run test
    stop_time = time.time()
    print('the func run time is %s'%(stop_time-start_time))
    return deco

    @timer#test=timer(test)
    def test():
    time.sleep(2)
    print('in the test')


    @timer
    def test2(name,age):
    time.sleep(1)
    print('test2',name,age)

    test()
    test2('ailice',33)
    #列表生成式
    print([i*2 for i in range(10)])
    # #生成器
    # a=(i*2 for i in range(10000000))
    # #下一个数值
    # print(a.__next__())
    # print(a.__next__())
    # print(a.__next__())
  • 相关阅读:
    两数之和
    swift 结构体
    打家劫舍II
    Swift的访问控制讲解
    swift版 二分查找 (折半查找)
    RAC(ReactiveCocoa)介绍(一)
    变位词
    双向循环链表
    单链表
    顺序链表(C++)
  • 原文地址:https://www.cnblogs.com/anhao-world/p/12952671.html
Copyright © 2011-2022 走看看