Skip to main content
 首页 » 编程设计

python之艰难地学习 Python Ex 25 : local variable/object assignment in functions

2024年10月01日6langtianya

我正在通过学​​习 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!

作为旁注,有一个彩蛋,它通过运行以下命令打印到控制台:import this。