我希望对2个整数进行加法运算,这两个整数也可能是空值,具体结果如下:
add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b
这个问题最符合Python风格、最简洁的表达方式是什么? 到目前为止我只有这样:
def add1(a, b):
if a is None:
return b
elif b is None:
return a
else:
return a + b
或者
def add2(a, b):
try:
return a + b
except TypeError:
return a if a is not None else b
有没有更简单的方法实现它?
int
类型或None
。在这个改变之后,它会错误地返回 None,当输入是 (0, None) 时。 - michailgames