python中的装饰器,python缓存装饰器,装饰器: 在不改
python中的装饰器,python缓存装饰器,装饰器: 在不改
装饰器:
在不改变元代码和调用方式的基础上增加新功能
函数中
内存地址 +():表示调用该函数
eg:def test(): print("==>")print(test)# test表示函数test()的内存地址
# wrapper 包装、包裹;decorator 装饰器、装饰
装饰器一般格式:
def wrapper(func): def deco():func()return deco @wrapper def index():print("欢迎来到我的世界!")index()
如何实现装饰器?
一、没有形参
defwrapper(func):#wrapper的执行结果是:返回deco的内存地址defdeco():func()print("add new function")returndeco#return返回的是deco的内存地址defindex():print("欢迎来到我的世界!")#result=wrapper(index)#result()index=wrapper(index) #index=decoindex() #index()=deco()>>> 欢迎来到我的世界!>>> add new function
二、源代码有形参
1、
def wrapper(func): #wrapper的执行结果是:返回deco的内存地址def deco(user,passwd): func(user,passwd) print("add new function") return deco #return返回的是deco的内存地址def index(user,passwd):print("欢迎来到我的世界!")index = wrapper(index) #index=decoindex(‘root‘,‘root‘) #index()=deco()>>> 欢迎来到我的世界!>>> add new function
2、
def wrapper(func): #wrapper的执行结果是:返回deco的内存地址def deco(*args,**kwargs): func(*args,**kwargs) print("add new function") return deco #return返回的是deco的内存地址def index(*args,**kwargs):print("欢迎来到我的世界!")index = wrapper(index) #index=decoindex(‘root‘,‘root‘) #index()=deco()>>> 欢迎来到我的世界!>>> add new function
三、装饰器有形参(在外边再加一个函数)
defdefault(engine):defwrapper(func):defdeco():my_engine = input(‘myengine:‘)ifengine == my_engine:user = input("username:")pwd = input("password:")if user == ‘root‘ and pwd == ‘root‘:func()else:print("用户名密码错误!")elif engine == ‘myism‘:print("this is myism engine")else:print("不属于mariadb引擎")return decoreturn wrapper@default(‘innodb‘)def index():print("欢迎来到我的世界!")index>>> myengine:innodb>>> username:root>>> password:root>>> 欢迎来到我的世界!
实例:
#在访问之前加一层验证:
def wrapper(func): def deco():user = input("username:")pwd = input("password:")if user == ‘root‘ and pwd == ‘root‘:func()else:print("用户名密码错误!")return deco @wrapper #官方指定装饰器语法。index = wrapper(index)def index():print("欢迎来到我的世界!")index()>>> username:root>>> password:root>>> 欢迎来到我的世界!>>> username:root>>> password:qwer>>> 用户名密码错误!
python中的装饰器
相关内容
- python之面向对象,python是面向对象吗,(一)构造方法和
- Python学习问题记录,,在学习Python的
- 吴裕雄 实战PYTHON编程(7),编程,import osf
- Python 进制转换,2进制转换8进制,#coding:ut
- Python vtk学习(1),,Vtk,(visua
- python--字符串格式化,python字符串处理,python的字符串
- python中文件操作,python打开文件并写入,1.创建和打开文
- 联合分组、子查询、视图、事务、python操作mysql、索引
- Python学习记录——Ubuntu(二)用户和用户组,,1.etc文件
- python笔记-----文件操作,python文件,文件操作创建一个文
评论关闭