我正在通过学习 Zed Shaw 的书《Learn Python The Hard Way》来学习 python2 的基础知识。在练习 25 中,作者给出了一些函数,例如:
def break_words(sentence):
words = sentence.split(' ')
return words
def print_first_word(words):
word = words.pop(0)
print word
我像这样缩短了函数:
def break_words(sentence):
return sentence.split(' ')
def print_first_word(sentence)
print break_words(sentence).pop(0)
想知道作者将 .split() 和 .pop() 分配给words/word 是否有原因?
谢谢
最佳答案
我认为唯一的原因是可读性(在他们看来)。
对于许多人来说,直接返回
它们也同样清楚,但这取决于编写代码的人或代码的编写对象。
我个人会采用您缩短它们的方法,但这是一个偏好问题。
接受 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 - 艰难地学习 Python Ex 25 : local variable/object assignment in functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000122/