Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python decorator修改的函数的返回值是否只能为非类型_Python_Decorator_Nonetype - Fatal编程技术网

python decorator修改的函数的返回值是否只能为非类型

python decorator修改的函数的返回值是否只能为非类型,python,decorator,nonetype,Python,Decorator,Nonetype,我编写了一个decorator来获取程序的运行时,但是函数返回值变为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

我编写了一个decorator来获取程序的运行时,但是函数返回值变为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
如果不使用decorator,则返回值是正确的

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
接受非类型。

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

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
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
或者你可以:

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)