@Advanced syntax python (decorator) grammar jelly beans.

python function decorator

As the name suggests, the decorator is used for the secondary processing of a function. For example, we have worked so hard to write a function and now we need to add new functions, so at this time, what do you do? Obviously, it is not worthwhile to change the code again if the amount of code is large. In other words, it is necessary to add the same function to multiple functions. If paste and copy are obviously not very efficient, this time the decorator is introduced.

Give a chestnut

Now we define a function

import time
def need_change():
	time.sleep(2)#让它沉睡2秒

Then we now need to add a timing function to calculate the running time of this program.
Change it so it looks like this

import time
def need_change():
	star=time.time()
	time.sleep(2)#让它沉睡2秒
	end=time.time()
	print(end-star)

Very good, successfully changed and added functions, so now I still have 10 such programs that need to add such functions.

Writing decorative functions

Our purpose is to get a new function with added functions, in this case, we directly define a function and this function can return a new function.

def decorate(func):
	def new_function():
		star=time.time()
		func()
		end=time.time()
		print(end-star)
	return new_function
		
	

So you can see that we return a new function directly.

import time
def need_change():
	time.sleep(2)#让它沉睡2秒

def decorate(func):
	def new_function():
		star=time.time()
		func()
		end=time.time()
		print(end-star)
	return new_function

need_change= decorate(need_change)
need_change()

Insert picture description here
But what should be noted here is that the need_change function is actually not the original, but the new_function function.
Otherwise you can look at this code;

import time
def need_change():
	time.sleep(2)#让它沉睡2秒

def decorate(func):
	def new_function():
		star=time.time()
		func()
		end=time.time()
		print(end-star)
	return new_function
print('我是这个函数%s'%need_change.__name__)

need_change= decorate(need_change)
need_change()

print('我是这个函数%s'%need_change.__name__)

Insert picture description here

The use of jelly beans

For more convenience, we can modify the code.

import time


def decorate(func):
	def new_function():
		star=time.time()
		func()
		end=time.time()
		print(end-star)
	return new_function
@decorate
def need_change():
	time.sleep(2)#让它沉睡2秒
need_change()


print('我是这个函数%s'%need_change.__name__)

This symbol @ is equivalent to

need_change= decorate(need_change)

Insert picture description here
Okay, that's all.

Guess you like

Origin blog.csdn.net/FUTEROX/article/details/107869159