【问题标题】:Whether the return value of a function modified by python decorator can only be Nonetypepython装饰器修改的函数返回值是否只能为Nonetype
【发布时间】:2019-02-12 08:18:00
【问题描述】:

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

【问题讨论】:

    标签: python decorator nonetype


    【解决方案1】:

    由于包装器替换被装饰的函数,所以还需要传递返回值:

    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
    

    【讨论】:

      【解决方案2】:

      或者你可以这样做:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-04
        • 2014-09-10
        • 2020-04-28
        • 2022-01-20
        • 2021-01-17
        • 2020-06-22
        • 2018-08-31
        • 2011-11-04
        相关资源
        最近更新 更多