我在浏览https://github.com/python/cpython/blob/master/Lib/datetime.py时偶然发现了一些类型检查函数(我简化了它们,原来是{u check}u int}字段)
def foo(year, month, day):
year = check_int(year)
month = check_int(month)
day = check_int(day)
check_int返回输入的值(如果是整数)-如果不是,则引发ValueError。让我缩短他们使用的函数:
def check_int(value):
if isinstance(value, int):
return value
if not isinstance(value, int):
raise TypeError('integer argument expected, got %s' % type(value))
我的问题是:回报声明背后的含义是什么?你当然可以把它当作
def check_int(value):
if not isinstance(value, int):
raise TypeError('integer argument expected, got %s' % value)
这将把foo函数改为(在这里不必定义变量,只需使用foo参数)
def foo(year, month, day):
check_int(year)
check_int(month)
check_int(day)
如果输入类型错误,这将引发TypeError—如果不是,则继续使用函数参数,而不必定义任何变量。那么,如果他们不修改输入变量,而只是简单地检查它,为什么还要返回输入变量呢
一般来说,我同意纯验证函数也可以是
void
,即不返回任何内容,并在需要时引发异常然而,在这种特殊情况下,
_check_int_field
函数实际上是这样使用的:这是有意义的,因为在
_check_int_field
中,它们是这样做的:所以函数实际上不仅仅是验证。在这种情况下,函数返回值是有意义的
相关问题 更多 >
编程相关推荐