python函数装饰器的使用

使用装饰器的一个好处就是可以对函数进行批量操作:

我们先写两个函数:

def func1():
    print 'This is func1'
def func2():
    print 'This is func2'    
func1()
func2()

'''
out:
This is func1
This is func2
'''

装饰器的基本使用:使用装饰器对这两个函数进行修改

def outer(func):
    def wrapper():
        print 'This is wrapper'
        func()
    return wrapper     

@outer
def func1():
    print 'This is func1'
@outer
def func2():
    print 'This is func2'    

func1()
func2()
'''
out:
This is wrapper
This is func1
This is wrapper
This is func2
'''

为装饰器添加参数

#加参数
def outer(func):
    #在wrapper()中添加函数所需的参数
    def wrapper(arg1,arg2):
        print 'This is wrapper'
        func(arg1,arg2)
    return wrapper    

#@outer = outer(func1())
@outer
def func1(arg1,arg2):
    print 'This is func1'
    print arg1+arg2
@outer
def func2(arg1,arg2):
    print 'This is func2'
    print arg1-arg2    

func1(4,2)
func2(4,2)

'''
out:
This is wrapper
This is func1
6
This is wrapper
This is func2
2
'''

使装饰器返回结果

#加返回值
def outer(func):
    def wrapper(arg1,arg2):
        print 'This is wrapper'
        result = func(arg1,arg2)
        return result
    return wrapper    

#@outer为语法糖,其本质是outer = outer(func())
@outer
def func1(arg1,arg2):
    print 'This is func1'
    return arg1+arg2
@outer
def func2(arg1,arg2):
    print 'This is func2'
    return arg1-arg2    

re1 = func1(4,2)
print re1
re2 = func2(4,2)
print re2

'''
out:
This is wrapper
This is func1
6
This is wrapper
This is func2
2
'''

未完待续………..

更多的请查看这篇文章:http://blog.csdn.net/mdl13412/article/details/22608283

还有这篇文章讲解的也非常好:http://www.cnblogs.com/cicaday/p/python-decorator.html

猜你喜欢

转载自blog.csdn.net/muwinter/article/details/77508673