EVE Light on Life

python之带参数装饰器

使用带参数装饰器即是在原有装饰器外面再加一层函数,直接看例子:

# -*- coding: utf-8 -*-

def deco(arg):
    if arg == 1:
        def _deco1(func):
            def _deco():
                print("1 decorator:before myfunc() called.")
                ret = func()
                print("1 decorator:after myfunc() called.")
                return ret
            return _deco
        return _deco1

    elif arg == 2:
        def _deco2(func):
            def _deco():
                print("2 decorator:before myfunc() called.")
                ret = func()
                print("2 decorator:after myfunc() called.")
                return ret
            return _deco
        return _deco2

@deco(2)   #相当于myfunc = deco(2)(myfunc)
def myfunc():
    print(" myfunc() called.")
    return 'ok'


if __name__ == '__main__':
    print myfunc()
    myfunc()

结果:

2 decorator:before myfunc() called.
 myfunc() called.
2 decorator:after myfunc() called.
ok
2 decorator:before myfunc() called.
 myfunc() called.
2 decorator:after myfunc() called.