Decorator for python3 functions

Decorator, as the name implies, is packaging. What can we do by wrapping the function? We can do some things before, during and after the target function call . For example, we want to count the execution time of a function.

def p():

  print('Hello World')

To count the execution time of function p, the most direct way is to modify it directly in the function body and add time calculation logic:

import time

def p(name):

  start = time.time()

  print('Hello %s'%name)

  end = time.time()

  print('spend time is %s'%(end-start))

If other functions also need to count the time consumption, then other functions also need to add repeated time calculation logic. The logic originally unrelated to the business invades the business code, the code is redundant and difficult to expand, and the public part is difficult to reuse.

If you add other statistics such as log, then the code needs to be refactored every time, the simplest we can extract the common part as a function:

import time

def show_time(func):

  start = time.time()

  func()

  end = time.time()

  print('spend time is %s'%(end-start))

show_time(p)

In this way, when we pass the target function into the public function, we can count the execution time of the target function, but the target function needs to explicitly call the public function, and the public function is exposed outside, and the parameter transfer of the target function is not flexible.

Then we can use python's decorator to wrap the function objective function:

import time
def show_time(func):
def proxy(*args,**kargs):
start=time.time()
print(args)
print(kargs)
func(args)
end=time.time()
print('spend %s'%(end-start))
return proxy
@show_time 
def test(name):
print(name)
time.sleep(3) Does
it feel a bit like a proxy mode? This is aspect-oriented programming, and it needs to be abstracted. Python functions can use decorators to seamlessly weave aspects Into the business logic, this completes the work of the aspect.
Life is too short, I use python.

Guess you like

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