|
发表于 2024-4-16 17:38:39
|
显示全部楼层
本帖最后由 jackz007 于 2024-4-16 17:44 编辑
- import time
- def timeslong(func):
- def call():
- start = time.time()
- print("It's time starting ! ")
- func() # 实际调用被装饰函数 myfunc()
- print("It's time ending ! ")
- end = time.time()
- return "It's used : %s." % (end - start)
- return call # 返回 timeslong() 内嵌装饰器函数 call() 的调用句柄,以便可以在外部调用。
- @timeslong # timeslong 装饰了 myfunc,当调用 myfunc() 时,Python 首先调用 timeslong(func) 获得 call 的调用句柄(return call),然后,实际调用内嵌函数 call(),在 call() 内,通过语句 func() 完成对被装饰函数 myfunc() 的调用,
- def myfunc():
- print("Hello FishC.")
- print(myfunc())
复制代码
不用装饰器的等效代码:
- import time
- def timeslong(func):
- def call():
- start = time.time()
- print("It's time starting ! ")
- func()
- print("It's time ending ! ")
- end = time.time()
- return "It's used : %s." % (end - start)
- return call
- def myfunc():
- print("Hello FishC.")
- print(timeslong(myfunc)()) # timeslong(myfunc) 就是内嵌函数 call 的调用句柄,加括号就是在调用内嵌函数 call()
复制代码 |
|