这段代码中的“返回结果”会影响此装饰器的结果吗?

时间:2019-07-20 07:18:05

标签: python return decorator

我今天遇到了一个关于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.

没有变化

2 个答案:

答案 0 :(得分:2)

下面的示例让我们理解-

  1. 装饰器内部函数,返回以下内容:

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

  1. 装饰器内部函数,不返回任何内容:
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!')

来源:

https://www.learnpython.org/en/Decorators

https://hackernoon.com/decorators-in-python-8fd0dce93c08

答案 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)