什么是装饰器
假设有函数A,B,C,已经全部编写完成,这时你发现A, B, C都需要同一个功能,这时该怎么办?
答: 装饰器
装饰器其实就是一个函数,不过这个函数的返回值是一个函数
个人理解,装饰器主要就是为了完成上边的这个功能,将A, B, C 函数包裹在另一个函数D中,D函数在A函数执行之前或之后,处理一些事情
#!/usr/bin/env python
#coding:utf-8
def SeparatorLine():
? ? print "############################"
#装饰器带参数函数带参数? ?
def DecratorArgFuncArg(f1,f2):
? ? def inner(func):
? ? ? ? def wrapper(arg):
? ? ? ? ? ? print "装饰器带参数函数带参数"
? ? ? ? ? ? f1()? ? ?
? ? ? ? ? ? result =? func(arg)
? ? ? ? ? ? f2()
? ? ? ? ? ? return result?
? ? ? ? return wrapper
? ? return inner
#装饰器带参数函数不带参数
def DecratorArgFuncNoArg(f1,f2):
? ? def inner(func):
? ? ? ? def wrapper():
? ? ? ? ? ? print "装饰器带参数函数不带参数"
? ? ? ? ? ? f1()? ? ?
? ? ? ? ? ? result=func()
? ? ? ? ? ? f2()
? ? ? ? ? ? return result
? ? ? ? return wrapper
? ? return inner
#函数没有参数的装饰器
def FuncNoArgDecrator(func):
? ? def wrapper():
? ? ? ? print "函数没有参数的装饰器"? ? ?
? ? ? ? func()
? ? return wrapper
#函数有参数的装饰器
def FuncArgDecrator(func):
? ? def wrapper(arg):
? ? ? ? print "函数有参数的装饰器"? ? ?
? ? ? ? func(arg)
? ? return wrapper
#函数有返回值的装饰器
def FuncReturnDecrator(func):
? ? def wrapper():
? ? ? ? print "函数有返回值的装饰器"? ? ?
? ? ? ? result=func()
? ? ? ? return result
? ? return wrapper
#这两个函数用
def login():
? ? print '开始登录'
?
def logout():
? ? print '退出登录'
@FuncArgDecrator
def Lee(arg):
? ? print 'I am %s' %arg
@FuncNoArgDecrator
def Marlon():
? ? print 'i am Marlon'
@DecratorArgFuncNoArg(login,logout)
def Allen():
? ? print 'i am Allen'?
@DecratorArgFuncArg(login,logout)
def Aswill(name):
? ? print 'I am %s' %name?
@FuncReturnDecrator
def Frank():
? ? return 'I am frank'
if __name__=='__main__':
? ? SeparatorLine()
? ? Lee('Lee')
? ? SeparatorLine()
? ? Marlon()
? ? SeparatorLine()
? ? Allen()
? ? SeparatorLine()
? ? Aswill('Aswill')
? ? SeparatorLine()
? ? result = Frank()
? ? print result
--------------------------------------分割线 --------------------------------------