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__())
  • 相关阅读:
    python中list的一种取值方式切片
    python之字典(Dictionary)
    表示数字
    自动收售货系统
    明明的随机数
    自守数
    等差数列
    计算字符个数
    字符统计
    Redraimen的走法
  • 原文地址:https://www.cnblogs.com/anhao-world/p/12952671.html
Copyright © 2011-2022 走看看