python函数之一 装饰器
装饰器的语法以@开始,接着是装饰器函数的名字和可选的参数。紧接着装饰器声明的是被修饰的函数和装饰函数的可选参数。如下
@decorator(dec_opt_args)
def funcToBeDecorated(func_opt_args):
.
.
对于多个装饰器,使用数学定义表示如下:
( g.f )(x) = g( f(x) )
对于Python中:
@g
@f
def foo():
.
.
等同于 g(f(foo))
简单函数装饰器
#!/usr/bin/env python
from time import ctime,sleep
def deco(func):
def wrappedFunc():
print '[%s] %s called' % (ctime(),func.__name__)
return func()
return wrappedFunc
@deco
def foo():
print 'foo called'
if __name__=='__main__':
foo()
########################################
localhost:~ army$ ./deco.py
[Sun Apr 13 16:20:01 2014] foo called
foo called
对带参数的函数进行修饰
eg:
#!/usr/bin/env python
from time import ctime,sleep
def deco(func):
def wrappedFunc(*argv):
print '[%s] %s called' % (ctime(),func.__name__)
return func(*argv)
return wrappedFunc
@deco
def add(a,b):
print a+b
if __name__=='__main__':
add(1,2)
########################################
localhost:~ army$ ./deco.py
[Sun Apr 13 16:25:01 2014] add called
3
装饰器带参数
装饰器带参数,需要增加一层包装
#!/usr/bin/env python
from time import ctime,sleep
def deco(arg):
def wrappedFunc(func):
def innerFunc(*argv):
print '[%s] %s called' % (arg , func.__name__)
return func(*argv)
return innerFunc
return wrappedFunc
@deco('module')
def foo(a,b,c):
print a+b+c
if __name__=='__main__':
foo(1,2,3)
########################################
localhost:~ army$ ./deco.py
[module] foo called
6