使用可选参数调用方法的最pythonic方法是什么?

Ada*_*dam 3 python optional-parameters python-2.7

假设我有一个带有一些可选参数的方法.

def foo(a, b=1, c=2, d=3)

如何调用它以便如果我的变量为None或空字符串,则使用默认值?

像下面这样的条件似乎是一个可怕的解决方案:

if b and not c and d:
    foo(myA, b = myB, d = myD)
elif b and not c and not d:
    ...
Run Code Online (Sandbox Code Playgroud)

在Java中,我会跳转到一个工厂,但看起来这就是默认情况下应该避免的情况.

Joh*_*ica 7

我会改变foo所以它用默认值替换空值.

def foo(a, b=None, c=None, d=None):
    if not b: b = 1
    if not c: c = 2
    if not d: d = 3
Run Code Online (Sandbox Code Playgroud)

请注意,这将把所有的"假y"的值作为默认值,不仅意味着None''0,False,[],等我个人收紧的界面和使用None,只None作为默认值.

def foo(a, b=None, c=None, d=None):
    if b is None: b = 1
    if c is None: c = 2
    if d is None: d = 3
Run Code Online (Sandbox Code Playgroud)