定义:本质是函数,就是为其他函数添加附加功能
原则:1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
例子:
import time
def timer(func):
def warpper(*args,**kwargs):
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is %s" % (stop_time-start_time))
return warpper
@timer #实际功能相当于func1 = timer(func1)
def func1():
time.sleep(3)
print("in the test1")
func1()
#结果
#in the test1
#the func run time is 3.0005111694335938
该函数满足装饰器的所有要求
装饰器=高阶函数+嵌套函数
高阶函数:
把一个函数名当做实参传给另外一个函数;返回值中包含函数名
def func1(func):
print(func)
def func2():
print(1)
func1(func2)
嵌套函数:
在一个函数的函数体内定义另一个函数
def func1():
print("in the func1")
def func2():
print("in the func2")
func2()
func1()
我的理解:
装饰器的实现方式,本质就是改变原函数的内存地址。通过高阶函数的返回值,将嵌套函数的内存地址赋给了原函数,而原函数的功能被记录在了嵌套函数中,通过嵌套函数添加了新功能,而且不改变源代码及原函数的调用方式。func1函数实际上已经变成了warpper函数,warpper函数的功能=func1原来的功能+添加的功能。但是func1的功能将会被永远改变,无法再单独实现func1的功能。
那如果函数要传参数进去怎么办呢?
简单!加个非固定参数就搞定了!
import time
def timer(func):
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 warpper
@timer
def func1():
time.sleep(1)
print("in the test1")
@timer
def func2(*args, **kwargs):
print(args, kwargs)
func1()
func2("Nick", daizhi="22", sex="male")
Step4 - Python基础4 迭代器、装饰器、软件开发规范
原文:http://www.cnblogs.com/Nick-Peggy/p/7156867.html