装饰器的使用

装饰器

装饰器顾名思义,一个可以起到装饰作用的工具

装饰器是谁?

装饰器本质还是一个函数,是一个嵌套的函数(闭包)

装饰器装饰谁?

装饰器装饰的还是函数

为什么要有装饰器?

装饰器(函数)是对现有函数功能的一个补充或增加,它可以更快速、更清晰、大批量的为函数增加功能

让代码更简单易懂,在不变更原有函数代码的情况下为现有函数功能进行增强

第一步理解闭包

#函数return了嵌套函数功能(一气阿成!)

def outer_func():
	message='hi'
	def inner_func():
		print(message)
	return inner_func()

my_func = outer_func()

#函数return了嵌套函数
(动作拆解!)

def outer_func():
	message='hi'
	def inner func():
		print(message)
	return inner_func

my_func =  outer_func()
my_func()

第二步理解注意这次带参数了!

def outer_func(msg):
	message = msg
	def inner_func():
		print(message)
	return inner_func
#这里return的是一个函数名字(实体),并没有(),换言之inner,他不会执行!
hello_func = outer_func('hello')
python func = outer_func('Python')
hello_func()
python_func()

第三步理解注意这次接近装饰器了!

#做一个可以接收“函数"做为参数的函数

def_deco_func(original func):
	def_wrapper_func():
		return original_func()
	return wrapper_func
#做一个独立的函数
```python
def show_age():
	print('I am 28')
#先把show_age带入函数
deco show age_deco_func(show_age)
#调用内部函数
deco_show_age()

第四步理解注意!这次是真的装饰器了!

#首先!创建装饰器逻辑

def deco_func(original func):
	def wrapper_func():
		return original_func()
	return wrapper_func

#使用装饰去装饰日+装饰器名字(函数名字)

@deco_func
def show_age():
	print('I am 28')

#使用常规的函数调用函数即可!

show age()

#注意!装饰器
没有改变你原有执行/调用的方式。
#deco show age deco func(show age)
#deco show age()

第五步理解继续推进-原始函数带参数怎么办?如何提升装饰器的宽容度

def deco_func(original func):
	def wrapper_func(*args,**kwargs):
		return original_func(*args,**kwargs)
	return wrapper_func
@deco_func
def show_age():
	print('I am 28')
@deco_func
def show_info(name,age):
	print(name,age)
@deco_func
def show_more(**kwargs):
	print(kwargs)
show_age()
show_info('zz',28)
show_more(school = 'PY',coding = 'PYTHON')

在这里插入图片描述

在这里插入图片描述

第七步理解 可否使用多重装饰器?也必须可以

#如何使用多个装饰器装饰器的装饰顺序?


def deco_code_name(func):
	def wrapper(msg):
		returnfunc(msg +007 ')
	return wrapper

def deco_first_name(func):
	def wrapper(msg):
		return_func(msg +James ')
	return wrapper
	
def deco_last_name(func):
	def wrapper(msg):
		return func(msg +Bond ')
	return wrapper

#内部功能函数依次由上到下执行

@deco_code_name
@deco_first_name
@deco_last_name
def whoami(msg):
	print('i am from',msg)
whoami('england')

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值