【问题标题】:Decorated function returns None装饰函数返回无
【发布时间】:2016-10-20 19:44:43
【问题描述】:

我有一个装饰器,它检查函数的参数是否为 int 类型。

def check_type_int(old_function):
    def new_function(arg):
        if not isinstance(arg, int):
            print 'Bad Type'    # raise TypeError('Bad Type')
        else:
            old_function(arg)
    return new_function

当我运行修饰函数时,它返回 None 而不是 int 值。

@check_type_int
def times2(num):
    return num*2

times2('Not A Number')  # prints "Bad Type"
print times2(2)         # prints "None"

最后一行应该打印4。有人可以发现我的错误吗?谢谢。

【问题讨论】:

  • 你为什么要明确检查这样的类型?如果类型无效,为什么print 而不是引发错误?

标签: python python-decorators


【解决方案1】:

你没有在装饰器内部return 任何来自new_function 的值,因此它默认返回None。只需更改此行:

old_function(arg)

return old_function(arg)

【讨论】:

  • 实际上你应该通过 *args 而不是 arg
  • 是的,我希望它是一个单参数函数。谢谢。
【解决方案2】:

由@eugeney 添加到answer:如果您在if 的两种情况下都使用return 会更容易:

if not isinstance(arg, int):
    return 'Bad Type'          # return 
else:
    return old_function(arg)   # return

还有这个:

print times2('2')                # prints Bad Type
print times2(2)                  # prints 4

【讨论】:

    【解决方案3】:

    你需要使用 *args 和 **kwargs

    def dec(function):
        def new_f(*args, **kwargs):
            return function(*args, **kwargs)
        return new_f
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-28
      • 2018-02-07
      • 2019-11-05
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2021-01-17
      相关资源
      最近更新 更多