Python编程语言中有哪些鲜为人知但很有用的特性?

尽量将答案限制在Python核心。 每个回答一个特征。 给出一个例子和功能的简短描述,而不仅仅是文档链接。 使用标题作为第一行标记该特性。

快速链接到答案:

参数解包 牙套 链接比较运算符 修饰符 可变默认参数的陷阱/危险 描述符 字典默认的.get值 所以测试 省略切片语法 枚举 其他/ 函数作为iter()参数 生成器表达式 导入该 就地值交换 步进列表 __missing__物品 多行正则表达式 命名字符串格式化 嵌套的列表/生成器推导 运行时的新类型 .pth文件 ROT13编码 正则表达式调试 发送到发电机 交互式解释器中的制表符补全 三元表达式 试着/ / else除外 拆包+打印()函数 与声明


当前回答

__slots__是一种节省内存的好方法,但是很难得到对象值的字典。想象下面这个物体:

class Point(object):
    __slots__ = ('x', 'y')

这个对象显然有两个属性。现在我们可以创建它的一个实例,并以这样的方式构建它的字典:

>>> p = Point()
>>> p.x = 3
>>> p.y = 5
>>> dict((k, getattr(p, k)) for k in p.__slots__)
{'y': 5, 'x': 3}

然而,如果point被子类化并且添加了新的槽,这将不起作用。但是Python会自动实现__reduce_ex__来帮助复制模块。这可以被滥用来获得价值的字典:

>>> p.__reduce_ex__(2)[2][1]
{'y': 5, 'x': 3}

其他回答

for line in open('foo'):
    print(line)

这相当于(但更好):

f = open('foo', 'r')
for line in f.readlines():
   print(line)
f.close()

可以从一组长度为2的序列构建字典。当你有一个值列表和数组列表时,这非常方便。

>>> dict([ ('foo','bar'),('a',1),('b',2) ])
{'a': 1, 'b': 2, 'foo': 'bar'}

>>> names = ['Bob', 'Marie', 'Alice']
>>> ages = [23, 27, 36]
>>> dict(zip(names, ages))
{'Alice': 36, 'Bob': 23, 'Marie': 27}

切片运算符中的step参数。例如:

a = [1,2,3,4,5]
>>> a[::2]  # iterate over the whole list in 2-increments
[1,3,5]

特殊情况x[::-1]是“x反转”的有用习语。

>>> a[::-1]
[5,4,3,2,1]

主要信息:)

import this
# btw look at this module's source :)

De-cyphered:

蒂姆·彼得斯的《Python之禅》 美总比丑好。 显性比隐性好。 简单比复杂好。 复杂胜过复杂。 扁平比嵌套好。 稀疏比密集好。 可读性。 特殊情况并不特别到可以打破规则。 尽管实用性胜过纯洁性。 错误绝不能悄无声息地过去。 除非明确保持沉默。 面对模棱两可,拒绝猜测的诱惑。 应该有一种——最好只有一种——明显的方法来做到这一点。 除非你是荷兰人,否则这种方式一开始可能并不明显。 现在总比没有好。 虽然永远不比现在更好。 如果实现很难解释,那就是一个坏主意。 如果实现很容易解释,这可能是一个好主意。 名称空间是一个非常棒的想法——让我们多做一些吧!

Doctest:同时进行文档和单元测试。

从Python文档中提取的示例:

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result

def _test():
    import doctest
    doctest.testmod()    

if __name__ == "__main__":
    _test()