这篇文章分为两部分,顶部是基于 OP 的新信息的更新答案 - 关于 eatAB() 不允许或不能修改。第二个答案是如果您有权修改函数本身,您将如何解决这个问题的原始答案。
更新的答案(您缺乏修改功能的访问/权限)
由于您无权在内部更改函数,但您知道它的签名 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(),因为它是函数的职责,而不是调用代码。解释在 cmets 中:
# 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 的改进建议。