def log(text):
if isinstance(text, str):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('The text is: %s' % text)
print('begin call')
a = func(*args, **kw)
print('end call')
return a
return wrapper
return decorator
else:
@functools.wraps(text)
a = text(*args, **kw)
理解这个问题的关键是,如果装饰器是@log('execute'),那么第一层函数log的参数text的值为'execure',第二层函数decorator的参数func的值为函数now;如果装饰器是@log,那么参数text的值为now,此时也就不需要第二层函数decorator了。
很多同学被text的名字所误导了,以为只能接收字符串作为参数。当你明白text既可以是字符串'execute'也可以是函数now的时候,你就知道这个问题怎么解决了。
Sign in to make a reply
飞侠100
def log(text):
if isinstance(text, str):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('The text is: %s' % text)
print('begin call')
a = func(*args, **kw)
print('end call')
return a
return wrapper
return decorator
else:
@functools.wraps(text)
def wrapper(*args, **kw):
print('begin call')
a = text(*args, **kw)
print('end call')
return a
return wrapper
理解这个问题的关键是,如果装饰器是@log('execute'),那么第一层函数log的参数text的值为'execure',第二层函数decorator的参数func的值为函数now;如果装饰器是@log,那么参数text的值为now,此时也就不需要第二层函数decorator了。
很多同学被text的名字所误导了,以为只能接收字符串作为参数。当你明白text既可以是字符串'execute'也可以是函数now的时候,你就知道这个问题怎么解决了。