我今天遇到了一个关于decorators
的教程,但是我不知道下面的代码中return result
有什么意义。因为,它的存在和删除对代码的输出不会产生任何影响。
def timer_decorator(original_func):
def wrapper_func(*args, **kwargs):
import time
t1 = time.time()
time.sleep(2)
result = original_func(*args, **kwargs)
t2 = time.time()
res = t2 - t1
print('Ran {} in {} secs.'.format(original_func.__name__, res))
return result # here
return wrapper_func
@timer_decorator
def display_info(name, age, email):
print('Display info for {}, {} years old [{}]'.format(name, age, email))
display_info('Marry Doe', 25, 'marry_doe@gmail.com')
无论是擦除return result
还是任一种输出,都是一样的。请告诉我我是否缺少什么。谢谢
edit:我编辑了display_info
函数,这次它返回了一些内容:
@timer_decorator
def display_info(name, age, email):
return 'Display info for {}, {} years old [{}]'.format(name, age, email)
再次,如果我删除return result
或只是让它在那里,就会得到以下结果:
Ran display_info in 2.0001468658447266 secs.
没有变化
答案 0 :(得分:2)
下面的示例让我们理解-
import time
def calculate_time_decorator(func):
def wrapper(*args, **kwargs):
print('Before Time {}!'.format(time.time()))
ret = func(*args, **kwargs)
print('After Time {}!'.format(time.time()))
return ret
return wrapper
在这里,我们的func()
是get_square()
,它将返回平方值。因此,我们希望此平方值将在ret
@calculate_time_decorator
def get_square(n):
print("given number is:", n)
return n * n
import time
def calculate_time_decorator(func):
def wrapper(*args, **kwargs):
print('Before Time {}!'.format(time.time()))
func(*args, **kwargs)
print('After Time {}!'.format(time.time()))
return ret
return wrapper
在这里,我们的func()
是myfunc()
,它没有返回任何值(因为它仅打印Not returning anything just printing!
)。因此,预计不会返回任何内容,因此,我们尚未在func(*args, **kwargs)
@calculate_time_decorator
def myfunc():
print('Not returning anything just printing!')
来源:
答案 1 :(得分:1)
对此进行思考,如果您从display_info返回一个数字,则可以将其分配给x,但如果删除返回结果,则将得到None。
def timer_decorator(original_func):
def wrapper_func(*args, **kwargs):
import time
t1 = time.time()
time.sleep(2)
result = original_func(*args, **kwargs)
t2 = time.time()
res = t2 - t1
print('Ran {} in {} secs.'.format(original_func.__name__, res))
return result # here
return wrapper_func
@timer_decorator
def display_info(name, age, email):
print('Display info for {}, {} years old [{}]'.format(name, age, email))
return 10
x = display_info('Marry Doe', 25, 'marry_doe@gmail.com')
print(x)