day4----装饰器

装饰器本质是函数,装饰其他函数,就是为其他函数添加附加功能。

原则:1.不能修改被装饰的函数的源代码
          2.不能修改被装饰的函数的调用方式
 
实现装饰器 知识储备
1.函数即“变量”
2.高阶函数
        a.把一个函数当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下 为其添加功能)
        b.返回值中包含函数名(不修改函数的调用方式)
3.嵌套函数
 
高阶函数+嵌套函数 =》 装饰器
 
高阶函数#变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
嵌套函数:在一个函数体内创建另外一个函数,这种函数就叫内嵌函数(基于python支持静态嵌套域)

 高阶函数
def bar():
    print 'in the bar'
def foo(func):
    res=func()
    return res
foo(bar)
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:DCC

import time
def bar():
    time.sleep(2)
    print("in the bar")
def test1(func):
    start_time=time.time()
    func()
    stop_time=time.time()
    print("run time is %s" %(stop_time-start_time))
test1(bar)

嵌套函数

y = 10
# def test():
#     y+=1
#     print y
def test():
    # global y
    y = 2
    print(y)
test()
print(y)
def dad():
    m = 1
    def son():
        n = 2
        print('--->', m + n)
    print('-->',m)
    son()
dad()

迭代器。 

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:DCC

import time

def timer(func):
    def deco(*args,**kwargs):
        # def warpper(*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 = timer(test1)
def test1():
    time.sleep(3)
    print("in the test1")

@timer # test2 = timer(test2) =deco
def test2(name,age):
    print(name,age)
    print("in the test2")

test1()
test2("dcc","2;5")
 
 
 
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/dcc001/p/5782521.html