我有一个装饰器,用于检查 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。有人可以发现我的错误吗?谢谢。
请您参考如下方法:
您不会返回来自装饰器内部new_function的任何值,因此它默认返回None。只需更改此行:
old_function(arg)
到
return old_function(arg)
