嵌套式if是什么更像Python?

2024-04-20 12:10:42 发布

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

两个函数的作用是一样的。在

def function1(self):
    a = self.get_a()
    b = self.get_b()
    c = self.get_c()
    r = None

    if a:
        r = a
        if b:
            r = b
            if c:
                r = c
            else:
                print("c not set.")
        else:
            print("b not set.")
    else:
        print("a not set.")

    return r



def function2(self):
    a = self.get_a()
    b = self.get_b()
    c = self.get_c()
    r = None

    if not a:
        print("a not set.")
        return r

    r = a
    if not b:
        print("b not set.")
        return r

    r = b
    if not c:
        print("c not set.")

    r = c
    return r

function1()创建非常长的行,如果嵌套的if越多,则与PEP8的78行长度限制冲突。在

function2()可能更难阅读/理解,并且有更多的返回语句。线路长度在这里没有问题。在

哪个更像Python?在


Tags: 函数selfnonegetreturnifdefnot
3条回答

您可以使用andor运算符的求值规则,例如:

>>> None or 4 or None or 5
4

>>> 4 and 5
5

所以你会有这样的东西:

^{pr2}$

我建议将I/O从逻辑代码中分解出来。在

python代码的一个原则是“扁平比嵌套好”。在此基础上,我认为function2()客观上更像Python。这可以在PEP-20: The Zen of Python中看到:

The Zen of Python

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

这可以通过在Python解释器中输入import this来看到。在

正如@Will的回答所暗示的,平淡更好。但是代码看起来并不很漂亮。一种更紧凑的代码怎么样?在

看看@Will的回答:

Readability counts.

Beautiful is better than ugly.

from collections import OrderedDict
def function3():
    my_dictionary=OrderedDict()
    my_dictionary['a'] = self.get_a()
    my_dictionary['b'] = self.get_b()
    my_dictionary['c'] = self.get_c()
    # ...
    r = None

    for name in my_dictionary.keys():
        value = my_dictionary[name]
        if not value:
            print("%s not set." % name)
            return r
        r = value
    return r

当然,这一点还可以进一步改善

相关问题 更多 >