Pythonic方法将可选参数映射为强制参数(如果不是)

2024-09-28 17:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个功能:

def func(foo, bar, nin=None, nout=None):
    if not nin:
        nin = bar
    if not nout:
        nout = bar
    return foo * nin / nout

它接受两个可选参数,如果没有传入,我需要将它们映射到另一个强制参数中。但这是Python的方式吗?有没有其他方法来获取检查并设置ninnout?在


Tags: 方法功能none参数returniffoodef
3条回答

None是输入的方式,您也可以接受零等。在

我认为你应该使用nin is None而不是nin == None,很多人会认为{}更像Python,但我个人认为两者都可以。在

我会做以下事情:

def func(foo, bar, nin=None, nout=None):
    nin = bar if nin is None else nin
    nout = bar if nout is None else nout
    return foo * nin / nout

如果你真的想缩短它,你可以这样做,例如:

nin = bar if nin is None else nin

请注意,这里我使用的是is,而不是真实性来测试None,否则,如果nin = 0会发生什么?这不是None,但仍然计算false-y(参见truth value testing),因此style guide的建议是:

Comparisons to singletons like None should always be done with is or is not ... beware of writing if x when you really mean if x is not None e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

相关问题 更多 >