Python function decorators can store the state information of decorated functions through instance attributes, global variables, non-local variables, and function attributes.
Description:
The number of function calls is counted through the decorator, and the call history is tracked with printing.
This decorator is implemented with the call( method of the class.
1) The decorator returns the instance object;
2) The number of constructor initialization calls is 0, and the incoming decorated function is recorded
3) Overload the call (method, count the number of calls by one per call, and call the decorator function and print the call information;
4) The returned instance object is assigned the name of the original function
5) Call the original function, which is equivalent to the instance name (), and the parenthetical operator automatically calls the call (method, so as to achieve the function of counting the number of calls.
Example
>>class counttrace:def __init__(self,func):
self.calls=0
self.func=func
Instance name () operation, automatically invoke call
def __call__(self,*args):
self.calls+=1
print('Call {}{ times'.format(func.__name__,wrapper.calls))
return func(*args,**kargs)
After defining the wrapper function, the property is assigned.
wrapper.calls=0
return wrapper
>counttrace
def testct(x):
print(x)
>counttrace
def testsquare(x):
print(x**2)
>testct('Ladder reading lines')
Call testct 1 time.
Ladder reading linesMultiple decorated functions each have a counter.
>testsquare(3)
Call testsquare 1 time.