不带参数的简单装饰器
def user_test(func):#此处func是bar函数 def wrapper(*args,**kwargs): print("%s is running" %func.__name__) return func(*args,**kwargs) return wrapper @user_test def bar(): print("i am bar") bar()
函数带参数的装饰器
def deco(func): def _deco(a, b): print("before myfunc() called.") a += 1 b += 1 ret = func(a, b) print("after myfunc() called. result: %s" % ret) return ret return _deco @deco def myfunc(a, b): print(" myfunc(%s,%s) called." % (a, b)) return a + b myfunc(1,2)
带参数的装饰器 :
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()
#这段代码是抄别人的