这两个函数做同样的事情。
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() 可能更难阅读/理解并且有更多的返回语句。行长在这里没有问题。
哪个更像pythonic?
请您参考如下方法:
Pythonic 代码的原则之一是“扁平优于嵌套”。在此基础上,我会说 function2() 客观上更像 Pythonic。这可以在 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 来查看。
