Python 学习笔记 ——装饰器

来源:互联网 发布:网络直播系统 编辑:程序博客网 时间:2024/05/02 02:52

装饰器也是一个函数(嵌套),用来装饰某个函数,来看下面的代码

import timedef time_count(func):    def wrapper():        start = time.time()        func()        end = time.time()        print 'This funnction costs:',end - start    return wrapperdef TellHi():    print 'Hello ervery body'Hi = time_count(TellHi)Hi()'''使用语法糖@来装饰函数@time_countdef TellHi():    print 'Hello ervery body'TellHi()'''

现在有一个需求,有无数个fun(),都需要添加验证,这样就需要装饰器来修饰来。

def outer(fun):    def wrapper(arg):        print '验证'        fun(arg)    return wrapper@outerdef Func1(arg):    print 'func1',arg@outerdef Func2(arg):    print 'func2',arg@outerdef Func3(arg):    print 'func3',argFunc1('xxxx')Func2('xxxx')Func3('xxxx')

如过函数有返回参数

def outer(fun):    def wrapper(arg):        print '验证'        res = fun(arg)        return res    return wrapper@outerdef Func1(arg):    print 'func1',arg    return 'return'@outerdef Func2(arg):    print 'func2',arg    return 'return'@outerdef Func3(arg):    print 'func3',arg    return 'return'print Func1('xxxx')print Func2('xxxx')print Func3('xxxx')
0 0
原创粉丝点击