signed

QiShunwang

“诚信为本、客户至上”

Python:decorator 函数装饰器

2020/8/19 21:22:39   来源:

文章目录

      • 装饰器:decorator
        • 被装饰函数携带参数
        • 装饰器携带参数

装饰器:decorator

# OOP单一职责原则
# 开闭原则:扩展功能,但是修改关闭,不修改源代码

# decorator 装饰器,本身是一个嵌套函数
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

被装饰函数携带参数

# target_func 被装饰函数
def decorator_for_paramfunc(target_func):
	# param 被装饰函数参数
	def __decorator(param):

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

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

装饰器携带参数

# args 装饰器参数
def decorator_with_param(args):
    # target_func 被装饰函数
	def _decorator(target_func):
        # param 被装饰函数参数
		def __decorator(param):
            # 打印
			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)