PYTHON decorator 3

A decorator is a function that has parameters? NO, the parameter is given to the function that generates the decorator.

 

def log(logfile='out.log'):
	def  log_decorateor(function):
		def wrapper_wrap_the_target_function(*args,**kwargs):
			log_str="LOG:#THE FUCTION '"+function.__name__+"()' WAS CALLED."
			print(log_str)
			with open(logfile,'a') as opened_file:
				opened_file.write(log_str+'\n')
			return function(*args,**kwargs)
		return wrapper_wrap_the_target_function
	return log_decorateor



#This is not @log, but @log()
@log()
def doSomething():
	print("Crackling operation")



@log(logfile='add.log')
def add(a,b):
	result=a+b
	print("{0}+{1}={2}".format(a,b,a+b))


if __name__ == '__main__':
	doSomething()
	add(10,20)

  

 

The @ above is not the name of the decorator, but the function that generates the decorator. By executing this function, a decorator is generated for the function that needs to be decorated below.

Guess you like

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