是否由python装饰器修改的函数的返回值只能为Nonetype

时间:2018-09-07 03:09:39

标签: python decorator nonetype

我写了一个装饰器来获取程序的运行时,但是函数的返回值变为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

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

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)

结果是:The correct rate is: 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: must be real number, not NoneType

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

2 个答案:

答案 0 :(得分:1)

或者您可以这样做:

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))
        print("The correct rate is: %f"%func(*args,**kw))
    return wrapper


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

答案 1 :(得分:0)

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

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