Python2.7、智能调理

Python 2.7, smart conditioning

这是我的情况:我得到了布尔值 ab 并且我有函数 eatAB() 可以吃 a 或 b 或 none.

这是我的问题:eatAB() 必须调用一次,我想要它 'smart-and-pretty'。我可以这样做:

if not a and not b:
    eatAB()
elif a and not b:
    eatAB(a=a)
elif not a and b:
    eatAB(b=b)
else:
    eatAB(a,b)

但对我来说,这个有点糟糕)有没有更漂亮、更好、更聪明或其他方式来做到这一点?感谢您的宝贵时间。

此 post 分为两部分,顶部是根据来自 OP 的新信息更新的答案 - 关于 eatAB() 不允许或不能修改。第二个答案是如果您有权修改函数本身,您将如何解决这个问题的原始答案。


更新答案(缺少 access/permission 修改功能)

由于您无权在内部更改函数,但您知道它的签名 eatAB(a=None,b=None) 我们希望遵循以下逻辑(来自问题):

  • 如果我们传递的值是真实的(例如True),我们要传递值
  • 如果该值不正确,我们要使用参数的默认值,即None

这可以使用以下表达式轻松完成:

value if condition else otherValue

在调用函数时使用它会给出以下内容:

a = False
b = True
eatAB(a if a else None, b if b else None)
# will be the same as calling eatAB(None, True) or eatAB(b=True)

当然,如果a和b的值本身来自一个条件,你可以直接使用那个条件。例如:

eatAB(someValue if "a" in myDictionary else None, someOtherValue if "b" in myDictionary else None)

原答案(可修改功能):

不知道 eatAB() 到底是做什么的,也不知道它是什么签名,我能推荐的最好的是以下内容。我相信您可以根据需要进行调整。

主要思想是将该逻辑移动到 eatAB() 中,因为它是函数的责任而不是调用代码。解释在评论中:

# for parameters a and b to be optional as you have shown, they must have a default value
# While it's standard to use None to denote the parameter is optional, the use case shown in the question has default values where a or b are False - so we will use that here.
def eatAB(a=False, b=False):
    # check if the parameters are truthy (e.g. True), in which case you would have passed them in as shown in the question.
    if a:
        # do some logic here for when a was a truthy value
    if b:
        # do some logic here for when b was a truthy value
    # what exactly the eatAB function I cannot guess, but using this setup you will have the same logic as wanted in the question - without the confusing conditional block each time you call it.

# function can then be called easily, there is no need for checking parameters
eatAB(someValue, someOtherValue)

感谢 Chris_Rands 提出的改进建议。