装饰器(http://egon09.blog.51cto.com/9161406/1836763)
1、装饰器:本质是函数;
装饰器(装饰其他函数),就是为其他函数添加附加功能;
原则:1.不能修改被装饰函数的源代码;
2.不能修改被装饰的函数的调用方式;
装饰器对被装饰的函数完全透明的,没有修改被装饰函数的代码和调用方式。
实现装饰器知识储备:
1.函数即“变量”;
2.高阶函数;
3.嵌套函数
高阶函数+嵌套函数=》装饰器
匿名函数(lambda表达式)
>>> calc = lambda x:x*3
>>> calc(2)
6
高阶函数:
a.把一个函数名当做实参传递给另外一个函数;
>>> def bar():
print("in the bar.....")
>>> def foo(func):
print(func)
>>> foo(bar)
<function bar at 0x7f8b3653cbf8>
b.返回值中包含函数名;
>>> import time
>>> def foo():
time.sleep(3)
print("in the foo.....")
>>> def main(func):
print(func)
return func
>>> t = main(foo)
<function foo at 0x7fb7dc9e3378>
>>> t()
in the foo.....
装饰器:
在不修改源代码的情况下,统计程序运行的时间:
import time
def timmer(func):
def warpper(*args,**kwargs): #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
@timmer #等价于test1 = timmer(test1),因此函数的执行调用是在装饰器里面执行调用的
def test1():
time.sleep(3)
print("in the test1")
test1()
运行结果如下:
in the test1
the func run time is 3.001983404159546
装饰器带参数的情况:
import time
def timmer(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 #返回内层函数名
@timmer
def test1():
time.sleep(3)
print("in the test1")
@timmer #test2 = timmer(test2)
def test2(name):
print("in the test2 %s" %name)
test1()
test2("alex")
运行结果如下:
in the test1
the func run time is 3.0032410621643066
in the test2 alex
the func run time is 2.3603439331054688e-05
装饰器返回值情况:
import time user,passwd = "alex","abc123" def auth(func): def wrapper(*args,**kwargs): username = input("Username:").strip() password = input("Password:").strip() if user == username and passwd == password: print("