艰难学习Python Ex 25:函数中的局部变量/对象赋值

时间:2017-10-29 12:22:34

标签: python python-2.7

通过研究Zed Shaw的书"学习Python的艰难之路"我正在学习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()到单词/单词?

谢谢

1 个答案:

答案 0 :(得分:2)

我认为唯一的原因是 可读性 (在他们看来)。

对于许多人来说,returning他们直接就会很清楚,但这取决于编写代码的人或编写代码的人。

你缩短它们的方法是我个人想要的,但这是一个偏好的问题。

the ZEN of Python获取指导:

  

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!

作为旁注,有一个复活节彩蛋,通过运行printed,这是import this到控制台。