Use of decorators - use decorators to record the number of times a function is called

 1 num=0
 2 def add_num(func):
 3     def wrapper(*args,**kw):
 4         global num
 5         num += 1
 6         print('begin add')
 7         res = func()
 8         print('end add')
 9         return res
10     return wrapper
11 
12 @add_num
13 def now():
14     print('now' )
 15 #call function
 16  for i in range(2 ):
 17      now()
 18      print (num)
Running result: 
begin add now end add
1 begin add now end add 2

Note that num should be modified with global here! declare global variables

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325069834&siteId=291194637