装饰后不再获得函数的返回值

时间:2018-07-14 12:53:01

标签: python python-decorators

Python 101 一书的第162页中,有一个有关记录装饰器功能的示例。代码如下:

import logging

def log(func):
   """
   Log what function is called
   """
   def wrap_log(*args, **kwargs):
      name = func.__name__
      logger = logging.getLogger(name)
      logger.setLevel(logging.INFO)

      # add file handler
      fh = logging.FileHandler("%s.log" % name)
      fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
      formatter = logging.Formatter(fmt)
      fh.setFormatter(formatter)
      logger.addHandler(fh)

      logger.info("Running function: %s" % name)
      result = func(*args, **kwargs)
      logger.info("Result: %s" % result)
      return func
   return wrap_log

@log
def double_function(a):
   """
   Double the input parameter
   """
   return a*2

if __name__=="__main__":
   value = double_function(2)

通常,代码末尾的value应该等于double_function的返回值,在这种情况下,该返回值等于4。但是,在执行后在控制台中检查它时,我发现它等于double_function本身,而不是它的返回值(是的,value成了函数)。

为什么会这样?我该如何使用double_function作为返回正确返回值的普通函数?

注意:我正在使用Python 3.6.5。

1 个答案:

答案 0 :(得分:2)

@ aran-fey是正确的

import logging

def log(func):
   """
   Log what function is called
   """
   def wrap_log(*args, **kwargs):
      name = func.__name__
      logger = logging.getLogger(name)
      logger.setLevel(logging.INFO)

      # add file handler
      fh = logging.FileHandler("%s.log" % name)
      fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
      formatter = logging.Formatter(fmt)
      fh.setFormatter(formatter)
      logger.addHandler(fh)

      logger.info("Running function: %s" % name)
      result = func(*args, **kwargs)
      logger.info("Result: %s" % result)
      return result  # Your error was you returned the function, not the result
   return wrap_log

@log
def double_function(a):
   """
   Double the input parameter
   """
   return a*2

if __name__=="__main__":
   value = double_function(2)
   print(value)