current position:Home>Python: decorator function decorator

Python: decorator function decorator

2022-02-02 14:14:57 Ice sky

Decorator :decorator

adopt Python Function decorator for , We can do this without changing the function source code and calling method , Update the function , Or the evaluation of relevant indicators , For example, the running time of functions, etc . Example :

# OOP Principle of single responsibility 
#  Opening and closing principle : Extend the functionality , But modify and close , Do not modify the source code 

# decorator  Decorator , Itself is a nested function 
def decorator(target_func):
	def __decorator():

		print("Dress decorator")
		target_func()
		print("Take off decorator")

		# print
	return __decorator

@decorator
def target_func():
	print("Hello!")
	return

about decorator There are two other situations :

  • The decorated function carries parameters
  • The decorator carries parameters

And a combination of these two situations .

The decorated function carries parameters

# target_func  Decorated function 
def decorator_for_paramfunc(target_func):
	# param  Decorated function parameters 
	def __decorator(param):

		print("Dress decorator")
		target_func(param)
		print("Take off decorator")

@decorator_for_paramfunc
def echo(message):
	print(message)

The decorator carries parameters

# args  Decorator parameters 
def decorator_with_param(args):
    # target_func  Decorated function 
	def _decorator(target_func):
        # param  Decorated function parameters 
		def __decorator(param):
            #  Print 
			print("decorator says %s" %(args))
			print("Dress decorator")
			target_func(param)
			print("Take off decorator")
		return __decorator
	return _decorator

@decorator_with_param('hello')
def echo(message):
	print(message)

copyright notice
author[Ice sky],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202021414549831.html

Random recommended