本文介绍了由python装饰器修改的函数的返回值是否只能为Nonetype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个装饰器来获取程序的运行时,但是函数的返回值变为Nonetype。

I wrote a decorator that gets the runtime of the program, but the function return value becomes Nonetype.

def gettime(func):
    def wrapper(*args, **kw):
        t1 = time.time()
        func(*args, **kw)
        t2 = time.time()
        t = (t2-t1)*1000
        print("%s run time is: %.5f ms"%(func.__name__, t))

    return wrapper

如果我不使用装饰器,则返回值正确。

If I don't use the decorator, the return value is correct.

A = np.random.randint(0,100,size=(100, 100))
B = np.random.randint(0,100,size=(100, 100))
def contrast(a, b):
    res = np.sum(np.equal(a, b))/(A.size)
    return res

res = contrast(A, B)
print("The correct rate is: %f"%res)

结果为:正确汇率为:0.012400

如果我使用装饰器:

@gettime
def contrast(a, b):
    res = np.sum(np.equal(a, b))/len(a)
    return res

res = contrast(A, B)
print("The correct rate is: %f"%res)

将会报告错误:

contrast run time is: 0.00000 ms

TypeError:必须为实数,而不是NoneType

当然,如果我删除了 print 语句,我可以获得正确的运行时间,但是 res 接受Nonetype。

Of course, if I remove the print statement, I can get the correct running time, but the res accepts the Nonetype.

推荐答案

由于包装器替换了装饰的函数,因此还需要传递返回值:

Since the wrapper replaces the function decorated, it also needs to pass on the return value:

def wrapper(*args, **kw):
    t1 = time.time()
    ret = func(*args, **kw)  # save it here
    t2 = time.time()
    t = (t2-t1)*1000
    print("%s run time is: %.5f ms"%(func.__name__, t))
    return ret  # return it here

这篇关于由python装饰器修改的函数的返回值是否只能为Nonetype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 14:23