python 装饰器详解

 

装饰器:

定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能

原则:1.不能修改被装饰的函数的源代码

   2.不能修改被装饰的函数的调用方式

import time

#嵌套函数
def foo():
print('in the foo')
def bar():
print('in the bar')
bar()
foo()


#装饰器
def timer(func):
def deco(*args,**kwargs):#timer(test) func=test *args,**kwargs带人参数

start_time = time.time()
func(*args,**kwargs)#run test
stop_time = time.time()
print('the func run time is %s'%(stop_time-start_time))
return deco

@timer#test=timer(test)
def test():
time.sleep(2)
print('in the test')


@timer
def test2(name,age):
time.sleep(1)
print('test2',name,age)

test()
test2('ailice',33)
#列表生成式
print([i*2 for i in range(10)])
# #生成器
# a=(i*2 for i in range(10000000))
# #下一个数值
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
posted @ 2020-05-24 21:07  安好_世界  阅读(143)  评论(0编辑  收藏  举报