def deco(*args):
def _deco(func):
def __deco():
print("before %s called [%s]." % (func.__name__, args))
func()
print(" after %s called [%s]." % (func.__name__, args))
return __deco
return _deco
@deco("mymodule") # 可用
def myfunc():
print(" myfunc() called.")
@deco() # 也可用
def myfunc2():
print(" myfunc2() called.")
@deco # 报错 TypeError: _deco() takes exactly 1 argument
def myfunc3():
print(" myfunc2() called.")
myfunc()
myfunc2()
myfunc3()
没有参数的
@deco
其实就是deco(myfunc3)
,所以需要对参数做个判断就行。