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

    #!usrinenvpython

    # -*- coding:utf-8 -*9

    import time

    def timer(func):   #定义装饰器函数

          def deco(*args,**kwargs):    #定义嵌套函数

                start_time=time.time()    

                func(*args,**kwargs)

                stop_time=time.time()

                print("the func run time is %s" %(stop_time-start_time))   #打印输出函数运行的结束时间

            return deco 

    @timer     #给test1函数添加功能,使用装饰器的方法进行编程

    def test1():              #定义函数test1

          time.sleep(2)     #延时2秒打印

          print("in the test1")

    def test2(*args,**kwargs):

          print("test2:",'alex','16')

    test1()       #调用test1函数

    test2()

    #需求:定义一个test1函数延时2秒钟打印,再使用装饰器扩展函数运行打印结束时间的功能;再定义函数test2,打印输出姓名和年龄两个变量;因此使用*args,**kwargs,进行不固定传参到func()函数当中,最后打印出的结果是:test1函数需要延时两秒钟打印输出in the test1并且计算出结束时间;test2函数需打印姓名和年龄。

  • 相关阅读:
    update语句中存在''语法书写方式
    CSS的代码风格
    CSS的语法规范
    CSS层叠样式表导读
    CSS简介
    HTML基本标签(下)
    HTML基本标签(上)
    HTML简介导读
    集合及其运用
    字典的镶嵌
  • 原文地址:https://www.cnblogs.com/lindong0602/p/9340414.html
Copyright © 2011-2022 走看看