python 装饰器

1.

>>> def deco(func):
...     print "In deco"
...     return func
...
>>> @deco
... def foo():
...     print "In foo"
...
In deco                 #因为deco()返回的 func 本身
>>>

>>>foo()
In foo

 

2.改进

>>> def deco(func):
...    print "in deco"
...    def wrapper():
...         print "wrapper start"
...         func()
...         print "wrapper end"
...    return wrapper
...
>>>
>>> @deco
... def foo():
...   print "foo"
...
in deco
>>>
>>>
>>> foo()
wrapper start
foo
wrapper end

在非交互模式下输出:

in deco
wrapper start
foo
wrapper end

 

 

3.怎么装饰不同参数的多个函数

def deco(func):
    def wrapper(*args, **kwargs):
        print "Wrap start"
        func(*args, **kwargs)
        print "Wrap end"
    return wrapper

@deco
def foo(x):
    print "In foo():"
    print "I have a para: %s" % x

@deco
def bar(x,y):
    print "In bar():"
    print "I have two para: %s and %s" % (x, y)

@deco
def foo_dict(x,z='dict_para'):
    print "In foo_dict:"
    print "I have two para, %s and %s" % (x, z)

if __name__ == "__main__":
    foo('x')
    bar('x', 'y')
    foo_dict('x', z='dict_para')

 

4.让装饰函数名更有意义些:带参数的装饰函数

def deco(arg):
    def _deco(func):
        def wrapper():
            print("before %s called [%s]." % (func.__name__, arg))
            func()
            print("after %s called [%s]." % (func.__name__, arg))
        return wrapper
    return _deco
 
@deco("module1")             #可以填插入类型
def insert_balance():
    print("insert into balance")
 
@deco("module2")
def insert_customer():
    print("insert into customer")

 

posted @ 2014-11-23 01:47  等风来。。  Views(193)  Comments(0Edit  收藏  举报
------------------------------------------------------------------------------------------------------------ --------------- 欢迎联系 x.guan.ling@gmail.com--------------- ------------------------------------------------------------------------------------------------------------