Wedge
As a python developer who can write functions, we are going to work in the company from today. Write a function, and it will be used by other developers.
def func1():
print('in func1')
At the end of the quarter, the leaders of the company will give performance bonus to everyone. They propose to review the results developed by everyone in this period. What is the standard of the review? Is to count the execution time of each function.
What are you going to do at this time?
When you think about it, it's easy to change the function:
import time
def func1():
start = time.time()
print('in func1')
print(time.time() - start)
func1()
Half a year since I came to the company, I have written 2000 + functions and changed them one by one. A week has passed. After the leader's review, I will delete them one by one... Another week passed... Is this disturbing?
You don't think you can. You can't bother to tell all the developers that now you add a sentence of calculating time to your original code?
import time
def func1():
print('in func1')
start = time.time()
func1()
print(time.time() - start)
Still can't, because this is too much trouble for the development colleagues.
Then what shall I do? You have an idea. You write a timer function...
import time
def timer(func):
start = time.time()
func()
print(time.time() - start)
def func1():
print('in func1')
def func2():
print('in func2')
timer(func1)
timer(func2)
Does that seem a lot easier? No matter how many functions we write, we can call this timing function to calculate the execution time of the function... Although the modification cost has become very small now, but for colleagues, the call mode of this function has been changed. If a colleague uses your method more than 2w times in his code because he believes in you, the boat of your friendship will turn completely after he modifies the code.
All you have to do is let your colleagues still call func1, but they can achieve the effect of calling timer method.
import time
def timer(func):
start = time.time()
func()
print(time.time() - start)
def func1():
print('in func1')
func1 =timer #It would be perfect if it could... It is a pity.
func1()
Unfortunately, the above code will report an error, because the timer method needs to pass a func parameter. We can't pass a parameter when assigning a value, because as long as we execute func1 = timer(func1), the timer method will directly execute, and the following sentence func1 has no meaning at all. Here, our thinking seems to be in a stalemate...
The forming process of decorator
import time
def func1():
print('in func1')
def timer(func):
def inner():
start = time.time()
func()
print(time.time() - start)
return inner
func1 = timer(func1)
func1()