Python 2.7,智能调节

2024-10-03 17:23:20 发布

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

这里是我的例子:我得到了布尔函数ab,我有函数eatAB(),它可以吃a或b,也可以不吃。你知道吗

这里是我的问题:eatAB()必须被调用一次,我希望它'聪明和漂亮'。我可以这样做:

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)

但对我来说,这一个吸点)有没有一个更漂亮,更好,更聪明或其他方式来做这件事?谢谢你的时间。你知道吗


Tags: and函数if方式时间notelse例子
1条回答
网友
1楼 · 发布于 2024-10-03 17:23:20

这篇文章分为两部分,顶部是一个更新的答案,基于OP的新信息-关于eatAB()不允许被修改或能够被修改。第二个答案是原始答案,如果您有权修改函数本身,您将如何解决这个问题。你知道吗


更新的答案(您没有权限/权限修改功能)

由于您没有权限在内部更改函数,但您知道它是signatureeatAB(a=None,b=None),因此我们希望遵循以下逻辑(从问题开始):

  • 如果我们传递的值是真的(例如True),我们就要传递这个值
  • 如果该值不为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)

感谢克里斯·兰兹的改进建议。你知道吗

相关问题 更多 >