【问题标题】:Learn Python the Hard Way Ex 25: local variable/object assignment in functions艰难地学习 Python Ex 25:函数中的局部变量/对象赋值
【发布时间】:2017-10-30 03:24:05
【问题描述】:

我正在通过学​​习 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 是否有原因?

谢谢

【问题讨论】:

  • 只是为了清楚。
  • 你到底为什么要学习 Python 2?它将于 2020 年正式停产。你应该学习 Python 3。然后,如果你需要它来处理(或阅读)遗留代码,你可以学习 Python 2。
  • @PM2Ring 因为作者建议先学习 Python 2 ...你让我对此感到困惑和沮丧 :)
  • FWIW,SO Python 聊天室常客do not recommend LPTHW。如果它对你有用,那就太好了,但请注意这本书有几个问题。 Zed 在那本书中严厉的反 Python 3 立场给我们留下了深刻的印象。 FWIW,他现在已经完成了 Python 3 版本,但他仍然不是 Python 3 的忠实粉丝。
  • 请注意,原始版本会给您留下一个缩短的words 列表,而您的版本将始终丢弃其余单词。

标签: python python-2.7


【解决方案1】:

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

对于许多人来说,直接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

【讨论】:

    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多