修饰函数returnsNone

Decorated function returns None

我有一个装饰器,用于检查函数参数的 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

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

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

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

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

您不会 return 装饰器内部 new_function 的任何值,因此它默认为 returns None。只需更改此行:

old_function(arg)

return old_function(arg)

@eugeney 添加到 :如果在 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

您需要使用 *args 和 **kwargs

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