代码之家  ›  专栏  ›  技术社区  ›  Alasdair

自深入Python以来对Python的更改

  •  12
  • Alasdair  · 技术社区  · 16 年前

    我一直在自学Python,通过 Dive Into Python 马克·皮格林。我完全推荐它,我也是 other Stack Overflow users .

    然而,最近一次深入Python的更新是在五年前。我期待着读这本新书 Dive into Python 3 当我切换到3.x时,但现在,使用django意味着我将坚持使用2.x。

    如果我曾经将深入研究Python作为学习该语言的主要资源,我很想知道我错过了Python的哪些新特性。我遇到的几个例子是

    • itertools

    还有什么我错过的吗?

    编辑:正如巴斯蒂安在他的回答中指出的那样,我可以阅读 What's New in Python 页面,但有时发现有关堆栈溢出的有用提示会很有趣,而不是在官方文档中费力地找到完整、全面的答案。

    6 回复  |  直到 8 年前
        1
  •  9
  •   cdleary    16 年前

    退房 What's New in Python . 它拥有2.x系列中的所有版本。根据Alex的评论,您需要查看所有Python2.xforX>2.

    日常编码要点:

    列举 :而不是做:

    for i in xrange(len(sequence)):
        val = sequence[i]
        pass
    

    for i, val in enumerate(iterable):
        pass
    

    这一点很重要,因为它适用于不可获取项的iterables(否则您必须在值迭代的同时使用递增索引计数器)。

    登录中 :基于打印的调试的合理替代方案,在Log4j样式库模块中标准化。

    布尔值 return True return 1 .

    发电机

    evens = (i for i in xrange(limit) if i % 2 == 0)
    

    assert [1, 2, 3, 4][::2] == [1, 3]
    

    设置

    pseudo_set = {'foo': None, 'bar': None}
    assert 'foo' in pseudo_set
    

    您现在可以执行以下操作:

    set_ = set(['foo', 'bar'])
    assert 'foo' in set_
    

    反向迭代 : reversed(sequence) sequence[::-1] .

    子流程 :统一您可能希望调用子流程的所有方式—捕获输出、馈送输入、阻塞或非阻塞。

    条件表达式

    a and b or c
    

    也就是说,当b是falsy时。 b if a else c

    :通过 with 陈述

    with open(filename) as file:
        print file.read()
    # File is closed outside the `with` block.
    

    :太多无法描述--请参阅下面的Python文档 str.format() .

        2
  •  6
  •   sunqiang    16 年前

    马克(这本书的作者)有 some comments 在这个问题上。我无耻地抄袭了这里的相关段落:
    “”“如果您选择Python 2,我只能推荐您使用“深入Python”第2-7、13-15和17章。本书的其余部分已经非常过时。”“”

        3
  •  3
  •   Shadow Wizard    14 年前

    以下是我所想到的答案的几个例子:

    条件表达式

    and-or trick ,2.5提供了一种新的书写方式 conditional expressions

    #and-or trick:
    x = condition and 'true_value' or 'false_value'
    
    #new in 2.5:
    x = 'true_value' if condition else 'false_value'
    

    字典中键的测试

    你有钥匙吗 is deprecated 赞成d键。

    >>>d={'key':'value','key2':'value2'}
    >>>'key1' in d
     True
    
        4
  •  2
  •   David Cournapeau    16 年前

    在2.4中添加了一些“次要”特性,这些特性在新的2.x python代码中非常普遍:decorator(2.4)和try/except/finally子句。在你做不到之前:

    try:
        do_something()
    except FunkyException:
        handle_exception():
    finally:
        clean_up()
    

    不过,这两种语言本质上都是语法上的甜点,因为您也可以这样做,只需多编写一点代码。

        5
  •  1
  •   Kredns    16 年前
    import antigravity
    

    See the documentation

        6
  •  0
  •   Bastien Léonard    16 年前

    我建议您阅读Python2.x中的内容?文件。

    • 新样式类(允许标准类型、子类型、属性等)。
    • 这个 with 关键字,它有助于分配和释放资源。