python3 闭包、装饰器实操备忘
#!/usr/bin/env python3
import time
#闭包:1.函数名被返回 2.函数内存在上级变量:这造成可保留之前的值或函数。也才有了装饰器
#装饰器(decorator):给函数作装饰,没有添加额外代码,却增加了新功能!
def outer(func):
def inner(*args,**kwargs):
func(*args)
return inner
@outer # 相当于a = outer(a)
a(*args,**kwargs)
#以上为装饰器代码模板!
'''
def foo(x,y):
s = x * y
s = s + x
print("这是一个功能函数!:%s",s)
time.sleep(1)
def bar(z):
print("这是一个功能函数!%s"%z)
time.sleep(1)
def outer(func): #给多个基础函数增加运行时间的功能!
#outer(func)以要扩展功能的函数作为参数传递,保留原函数代码块func(*arg)作用!此参数直接传给到下级函数!
def inner(*args): #新增功能后的函数!故参数须与原函数一致!以*args或**kwargs接收不定常变量,以避免出错!
start_time = time.time()
func(*args) #调用新函数时,执行的还是原代码块!
end_time = time.time()
spend_time = end_time - start_time
print("运行程序所需时间:%s"%(spend_time))
for i in args:
print(i)
return inner
foo = outer(foo)
foo(8,3)
'''
'''
def show_time(f):
def inner(x,y):
start_time = time.time()
f(x,y)
end_time = time.time()
spend_time = end_time - start_time
print("运行程序所需时间:%s"%(spend_time))
return inner
foo = show_time(foo)
foo(3,8)
'''