代码之家  ›  专栏  ›  技术社区  ›  ChynaJake

Python 2.7,智能调节

  •  -1
  • ChynaJake  · 技术社区  · 7 年前

    我的情况是:我得到了布尔值 a b 我有功能 eatAB() 它们可以吃a或b,也可以不吃。

    这是我的问题: 必须叫一次,我希望它“聪明漂亮”。我可以这样做:

    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)
    

    但对我来说,这个有点糟糕)有没有更漂亮、更好、更聪明或其他的方法?谢谢你的时间。

    1 回复  |  直到 7 年前
        1
  •  0
  •   user955340 user955340    7 年前

    这篇文章分为两部分,顶部是根据OP的新信息更新的答案 eatAB() 不允许或无法修改。第二个答案是原始答案,如果您有权修改函数本身,您将如何解决这个问题。


    更新的答案(您缺乏修改功能的访问/权限)

    因为您没有权限在内部更改函数,但您知道它的签名 eatAB(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)
    

    感谢Chris_Rands提出的改进建议。