生病停了几天时间-装饰器

#!\usr\bin\env\python # -*- coding:utf-8 -*9

import time #调用一个time模块

def timer(func): #装饰器timer,装饰器的构成即为:高阶函数+嵌套函数

      def deco(*arg,**kwarg): #嵌套函数

           strat_time =time.time() #开始时间

           func(*arg,**kwarg) #定义两个不固定的参数

           stop_time=time.time() #结束时间

           print("the func run time is %s" %(stop_time-start_time))

       return deco

@timer #调用装饰器

def test1(): #该函数的功能:延时3秒打印

      time.sleep(3)

      print("in the test1")

def test2(name,age):

print("pengdonghua","age=21")

 

#需求:定义了test1函数后,我想再定义函数test2,并且给test2函数加上装饰器;如果test2函数中定义两个变量,则装饰器中需有相应的存放位置,再比如我要定义test3函数中有三个变量,在装饰器中该如何实现呢?采用不固定参数进行传参!!! *arg **kwargs test1() #调用test1函数 test2()

总结: 装饰器的本质:函数即变量 原则:1.不改动源代码,2.不改变函数的调用方式 高阶函数的判定条件:1.返回值后面带有函数 2.一个函数可以接收另一个函数作为参数 嵌套函数:使用def声明的两个函数以上

posted on 2018-07-13 10:12  凛冬08  阅读(91)  评论(0编辑  收藏  举报

导航