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中的装饰器

评论关闭