python中的装饰器

装饰器:

  在不改变元代码和调用方式的基础上增加新功能
函数中
  内存地址 +():表示调用该函数

eg:
def test():
  print("==>")
print(test)
# test表示函数test()的内存地址

# wrapper 包装、包裹;decorator 装饰器、装饰

装饰器一般格式:

def 	wrapper(func):    
	def 	deco():
			func()
	return deco 
	      
@wrapper      
def index():
	print("欢迎来到我的世界!")
index()

如何实现装饰器?
一、没有形参

def	wrapper(func):		#wrapper的执行结果是:返回deco的内存地址
	def	deco():
		func()
		print("add  new  function")
	return	deco		#return返回的是deco的内存地址
	
def	index():
	print("欢迎来到我的世界!")
	
#result=wrapper(index)
#result()
index=wrapper(index)     #index=deco
index()                  #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=deco
index('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=deco
index('root','root')                    #index()=deco()

>>> 欢迎来到我的世界!
>>> add  new  function

三、装饰器有形参(在外边再加一个函数)

def	default(engine):
	def	wrapper(func):
		def	deco():
			my_engine = input('myengine:')
			if	engine == 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 deco
	return 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
>>> 用户名密码错误!
作者:无荨

-------------------------------------------

个性签名:学IT,就要做到‘活到老学到老’!

如果觉得这篇文章对你有小小的帮助的话,别忘记点个“推荐”哦!

原文地址:https://www.cnblogs.com/twoo/p/11661765.html