【发布时间】: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而不是引发错误?