|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
>>> import time
>>>
>>> def time_master(func):
... def call_func():
... print("开始运行程序")
... start = time.time()
... func()
... stop = time.time()
... print("结束程序...")
... print(f"一共耗费了{(stop - start):.2f} 秒。")
... return call_func
...
>>> @time_master
... def myfunc():
... time.sleep(2)
... print("I love fishC")
...
>>> myfunc()
开始运行程序
I love fishC
结束程序...
一共耗费了2.00 秒。
>>> def myfunc():
... time.sleep(3)
... print(" I love you")
...
>>> myfunc = time_master(myfunc)
>>> myfunc()
开始运行程序
I love you
结束程序...
一共耗费了3.00 秒。
>>> # 这个就是装饰器的实现原理啦~
>>> 多个装饰器也可以用在同一个函数上:
>>> def add(func):
... def inner():
... x = func()
... return x + 1
... return inner
...
>>>
>>> def cube(func):
... def inner():
... x = func()
... return x * x * x
... return inner
...
>>>
>>> def square(func):
... def inner():
... x = func()
... return x * x
... return inner
...
>>> @add
... @cube
... @square
... def test():
... return 2
...
>>> print(test())
65
>>> print(test())
65
>>> # 先计算平方(square 装饰器),再计算立方(cube 装饰器),最后再加 1(add 装饰器)。
>>> >>>
>>> # 如何给装饰器传递参数呢?
>>> # 添加多一层嵌套函数来传递参数:
>>>
>>> import time
>>>
>>> def loger(msg):
... def time_master(func):
... def call_func():
... start = time.time()
... func()
... stop = time.time
... print(f"[{msg}]一共耗费了{(stop - start):.2f}")
... return call_func
... return time_master
...
>>> def logger(msg):
... def time_master(func):
... def call_func():
... start = time.time()
... func()
... stop = time.time()
... print(f"[{msg}]一共耗费了{(stop - start):.2f}")
... return call_func
... return time_master
...
>>>
>>> @logger(msg="A")
... def funA():
... time.sleep(5)
... print("正在调用funA...")
...
>>> @logger(msg="B")
... def funB():
... time.sleep(6)
... print("正在调用funB...")
...
>>> funA()
正在调用funA...
[A]一共耗费了5.01
>>> funB()
正在调用funB...
[B]一共耗费了6.00
>>> # 这里其实就是给它裹多一层嵌套函数上去,然后通过最外层的这个函数来传递装饰器的参数。
>>> # 这样,logger(msg="A") 得到的是 timemaster() 函数的引用,然后再调用一次,并传入 funA,也就是这个 logger(msg="A")(funA),得到的就是 call_func() 函数的引用,最后将它赋值回 funA()。
>>> |
|