如何写一个装饰器?装饰器是一个闭包,分为两层函数,写法分两步:

第一步,外层函数,参数是函数名(被修饰的函数),返回值是内层函数

第二步,内层函数,参数是被修饰函数的参数,一般使用*args,**kwargs代替,返回值是被修饰函数返回值

 

例如:

 1 import time
 2 
 3 
 4 # 一,外层函数,装饰器函数名称,参数是一函数名(被修饰函数),返回值是内层函数名
 5 def timethis(func):
 6     #二,内层函数,实现装饰器的功能,参数是原函数参数,返回值是原函数返回值result
 7     def wrapper(*args,**kwargs):
 8         start=time.time()
 9         result=func(*args,**kwargs)
10         end=time.time()
11         print(func.__name__,end-start)
12         return result
13     return wrapper
14 
15 @timethis
16 def countdown(n):
17     while n>0:
18         n-=1
19 
20 countdown(100000000)

 

相关文章:

  • 2022-03-05
  • 2021-09-15
  • 2021-07-31
  • 2021-09-20
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-28
  • 2022-03-07
  • 2021-12-31
  • 2021-05-29
  • 2018-12-12
  • 2021-09-18
  • 2022-12-23
相关资源
相似解决方案