python 函数返回值nonetype_由python装饰器修改的函数的返回值是否只能为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)

The result is:The correct rate is: 0.012400

And if i use the decorator:

@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)

There will report a error:

contrast run time is: 0.00000 ms

TypeError: must be real number, not 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值