标签:time() **kwargs return 初识 源码 fun rgs wrap 开放封闭原则
用来装饰的工具
在不改变源代码及调用方式的基础上额外增加新的功能
开放封闭原则:
扩展是开放的(增加新功能)
修改源码是封闭的(修改已经实现的功能)
import time
start_time = time.time()
def func():
time.sleep(2)
print("asdf")
func()
print(time.time() - start_time)
start_time = time.time()
def foo():
time.sleep(3)
print("qwer")
foo()
print(time.time() - start_time)
def times(f):
start_time = time.time()
f()
print(time.time() - start_time)
def foo():
time.sleep(3)
print("asdf")
s = foo
foo = times
foo(s)
def times(f):
def inner():
start_time = time.time()
f()
print(time.time() - start_time)
return inner
def foo():
time.sleep(1)
print("asdf")
foo = times(foo)
foo()
def wrapper():
def inner():
print(1)
return inner
print(wrapper()())
def wrapper(f):
def inner():
f()
return inner
def func():
print("123456")
func = wrapper(func)
func()
import time
def wrapper(f):
def inner(*args,**kwargs):
start_time = time.time()
f(*args,**kwargs)
print(time.time() - start_time)
return inner
def func(*args,**kwargs):
print(f"这是{args,kwargs}函数")
time.sleep(2)
func = wrapper(func)
func("alex","wusir")
import time
def wrapper(f):
def inner(*args,**kwargs):
start_time = time.time()
f(*args,**kwargs)
print(time.time() - start_time)
return inner
@wrapper
def func(*args,**kwargs):
print(f"这是{args,kwargs}函数")
time.sleep(2)
@wrapper
def foo(*args,**kwargs):
print(f"这是{args,kwargs}函数,123456")
time.sleep(3)
func("alex","ahfe")
foo("alex1","faikewfhn")
def func(a): #a是要被装饰的函数名
def foo(*args,**kwargs):
"装饰之前的操作"
ret = a(*args,**kwargs)
"装饰之后的操作"
return ret
return foo
@func
def f1(*args,**kwargs):
print(f"这是一个{args}")
return "我可以返回了"
f1(1,2,3,34,4,5)
语法糖必须放在被装饰的函数正上方
@wrapper 就等于 func = wrapper(func)
@wrapper 就等于 foo = wrapper(foo)
标签:time() **kwargs return 初识 源码 fun rgs wrap 开放封闭原则
原文地址:https://www.cnblogs.com/beichen123/p/11247130.html