decorator

请编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志。

再思考一下能否写出一个@log的decorator,使它既支持:
@log
def f():
    pass
又支持
@log('execute')
def f():
    pass

 

def metric(ar = None):
	def decorator(func):
		@functools.wraps(func)
		def wrapper(*args, **kw):
			if ar != None:
				print('begin call %s %s'%(func.__name__, ar))
			else:
				print('begin call %s'%func.__name__)
			f = func(*args, **kw)
			if ar != None:
				print('end call %s %s'%(func.__name__, ar))
			else:
				print('end call %s'%func.__name__)
			return f
		return wrapper
	return decorator

调用:

decorator_第1张图片

 decorator_第2张图片

 

你可能感兴趣的:(decorator)