标签:
def myfunc()
print(‘myfunc() called.")
myfunc()
def deco(func):
print(‘before myfunc() called.‘)
func()
print(‘after myfunc() called‘)
def myfunc():
print(‘myfunc() called‘)
myfunc=deco(myfunc)#最重要的一步,修饰器就是一个函数,一个容器,用来放进其他函数修饰,改变,在函数前后添加内容的
def deco(func):
print(‘before myfunc() called.‘)
func()
print(‘after myfunc() called.‘)
return func
@deco
def myfunc():
print(‘myfunc() called‘)
def deco(func):
def _deco():
print(‘before myfunc() called.‘)
func()
print(‘after myfunc() called.‘)
return _deco
@deco
def myfunc():
print(‘myfunc() called‘)
myfunc()
def deco(func):
def _deco(a,b):
print(‘before myfunc() called.‘)
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(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 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)
myfunc2(1,2,3)
总的来说,就是把修饰器第二层的固定参数,改为(*args,**kwargs),被修饰函数就可以接受不确定数量的参数了
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(‘module1‘)
def myfunc():
print(‘myfunc() called‘)
@deco(‘module2‘)
def myfunc2():
print(‘myfunc2() called‘)
myfunc()
myfunc2()
解析:如果修饰器带有参数,那么修饰器需要三层,第一层,args是修饰器的参数,第二层参数是传进被修饰函数,第三层没有参数
标签:
原文地址:http://www.cnblogs.com/thouger/p/5931635.html