Python: 装饰器
Example#!/usr/bin/env pythonimport functoolsdef log_v1(arg):if callable(arg):func = arg@functools.wraps(func)def wrapper(*args, **kw):print 'call %s(
·
Example
#!/usr/bin/env python
import functools
def log_v1(arg):
if callable(arg):
func = arg
@functools.wraps(func)
def wrapper(*args, **kw):
print 'call %s()' % (func.__name__)
print "begin call"
func(*args, **kw)
print "end call"
return wrapper
else:
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s()' % (arg, func.__name__)
print "begin call"
func(*args, **kw)
print "end call"
return wrapper
return decorator
def log_v2(arg):
if isinstance(arg, str):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s()' % (arg, func.__name__)
print "begin call"
func(*args, **kw)
print "end call"
return wrapper
return decorator
else:
func = arg
@functools.wraps(func)
def wrapper(*args, **kw):
print 'call %s()' % (func.__name__)
print "begin call"
func(*args, **kw)
print "end call"
return wrapper
#@log_v2
@log_v1
def fa():
print "---> fa()"
#@log_v2('execute')
@log_v1('execute')
def fb():
print "---> fb()"
if __name__ == "__main__":
fa()
fb()
Output
call fa()
begin call
---> fa()
end call
execute fb()
begin call
---> fb()
end call
更多推荐
已为社区贡献2条内容
所有评论(0)