python:装饰器

装饰器

前言

装饰器字面理解:

本质:是一个函数

功能:装饰其他函数,为其他函数添加附加功能。

原则

(1)不能修改被装饰的函数的源代码。

(2)不能修改被装饰的函数的调用方式。

  总的来说:装饰器对于被装饰的函数来说就是透明的,被装饰函数既没有被改动,也没有被修改调用的方式,装被装饰函数感觉不到装饰器的存在。

装饰器的储备知识

1、函数即“”变量”。

定义一个函数,相当于把这个函数体赋值给一个变量,即函数名。

变量的回收机制:不引用时,python的计数器就定时清理。

2、高阶函数

a、 把一个函数名当做实参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

b、返回值中包含函数名(不修改函数的调用方式)

3、嵌套函数

高阶函数+嵌套函数=》装饰器

变量:

存在内存中。如:x=1,1是在内存中实实在在存在的,x则是该内存房间的门牌号。

装饰器

1、无返回值,无参数

import  time

def timer(fun):
    def deco():
        start_time=time.time()
        fun()
        stop_time=time.time()
        print("the fun time is %s"%(stop_time-start_time))
    return deco
@timer
def  test1():
    time.sleep(3)
    print("in the test1")
@timer
def  test2():
    time.sleep(3)
    print("in the test2")

test1()
test2()

>>>>>>>>>>

in the test1
the fun time is 3.0081706047058105
in the test2
the fun time is 3.000171422958374

 2、无返回值,有参数

3、有返回值

posted @ 2017-06-19 15:09  蜗牛散步2017  阅读(123)  评论(0编辑  收藏  举报