小编mic*_*mes的帖子

添加数字时处理无

我想添加2个整数,也可以是None,结果如下:

add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b
Run Code Online (Sandbox Code Playgroud)

什么是最诡异,最简洁的表达方式?到目前为止,我有:

def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b
Run Code Online (Sandbox Code Playgroud)

要么

def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b
Run Code Online (Sandbox Code Playgroud)

有没有更短的方法来实现它?

python nonetype

4
推荐指数
2
解决办法
996
查看次数

标签 统计

nonetype ×1

python ×1