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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值