首页 > 代码库 > python装饰器

python装饰器

示例一:

# coding=utf8

def deco(func):
  # 参数不确定的函数
def _deco(*args, **kwargs): print(before %s called. % func.__name__) ret = func(*args, **kwargs) print(after %s called. result: %s % (func.__name__, ret)) return _deco @deco def myfunc(a, b): print(myfunc(%s, %s) called. % (a, b)) return a + b @deco def myfunc2(a, b, c): print(myfunc2(%s, %s, %s) called. % (a, b, c)) return a + b + c myfunc(1, 2) myfunc(3, 4) myfunc2(1, 2, 3) myfunc2(3, 4, 5)

 

让装饰器带参数

 

# coding=utf8

# 让装饰器带参数
def deco(arg):
    def _deco(func):
        def __deco():
            print(before %s called [%s]. % (func.__name__, arg))
            func()
            print(after %s called [%s]. % (func.__name__, arg))
        return __deco
    return _deco

@deco(mymodule)
def myfunc():
    print(myfunc() called.)

@deco(module2)
def myfunc2():
    print(myfunc2() called.)

myfunc()
myfunc2()

 

python装饰器