python 装饰器

来源:互联网 发布:怎样开淘宝网店 编辑:程序博客网 时间:2024/05/22 11:58

在python中,通过简单的语法可以快速实现装饰函数和装饰类的模式.

装饰器是一种透明扩充类或者函数功能的一种设计模式,下面看Python中装饰器的使用

装饰基本函数

# 装饰函数def deco(func):    print 'deco()是一个装饰函数'    return func # 执行被装饰函数# 被装饰函数@decodef foo():    print 'foo()'# 调用被装饰函数时,会自动回调装饰函数foo()# 相当与deco(foo)"""deco()是一个装饰函数foo()"""

装饰带参数函数

# 对带参数的函数进行装饰def deco(func):    def _deco(a, b): # 定义一个内部函数用于填充参数        print 'call func before'        res = func(a, b)        print 'call func end ,result is %d' % res        return res    return _deco# 被装饰函数@decodef add(a, b):    print '%s + %s' % (a, b)    return a + badd(1, 2)"""call func before1 + 2call func end ,result is 3"""

让装饰器带参数

# 让装饰器带参数def deco(arg):  # 此处参数为装饰器传递进来的    def _deco(func):        def _deco2():            print 'before %s call, args is %s' % (func.__name__, arg)            func()            print 'call end'        return _deco2    return _deco@deco('module1')def foo():    print 'foo called'foo()"""before foo call, args is module1foo calledcall end"""
1 0