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

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

快速链接到答案:

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


当前回答

隐式连接:

>>> print "Hello " "World"
Hello World

当你想让一个很长的文本适合脚本中的几行时很有用:

hello = "Greaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Hello " \
        "Word"

or

hello = ("Greaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Hello " 
         "Word")

其他回答

你可以用类装饰函数——用类实例替换函数:

class countCalls(object):
    """ decorator replaces a function with a "countCalls" instance
    which behaves like the original function, but keeps track of calls

    >>> @countCalls
    ... def doNothing():
    ...     pass
    >>> doNothing()
    >>> doNothing()
    >>> print doNothing.timesCalled
    2
    """
    def __init__ (self, functionToTrack):
        self.functionToTrack = functionToTrack
        self.timesCalled = 0
    def __call__ (self, *args, **kwargs):
        self.timesCalled += 1
        return self.functionToTrack(*args, **kwargs)

序列乘法和反射的操作数

>>> 'xyz' * 3
'xyzxyzxyz'

>>> [1, 2] * 3
[1, 2, 1, 2, 1, 2]

>>> (1, 2) * 3
(1, 2, 1, 2, 1, 2)

我们用反射(交换)操作数得到相同的结果

>>> 3 * 'xyz'
'xyzxyzxyz'

它是这样工作的:

>>> s = 'xyz'
>>> num = 3

要计算表达式s * num,解释器调用s.___mul___(num)

>>> s * num
'xyzxyzxyz'

>>> s.__mul__(num)
'xyzxyzxyz'

计算表达式num *的解释器调用num. __mul___(s)

>>> num * s
'xyzxyzxyz'

>>> num.__mul__(s)
NotImplemented

如果调用返回NotImplemented,则解释器调用 如果操作数具有不同类型,则反射操作s. __rmul___(num)

>>> s.__rmul__(num)
'xyzxyzxyz'

看到http://docs.python.org/reference/datamodel.html object.rmul

条件赋值

x = 3 if (y == 1) else 2

正如它听起来的那样:“如果y是1,则赋3给x,否则赋2给x”。注意,括号不是必需的,但是为了可读性,我喜欢它们。如果你有更复杂的东西,你也可以把它串起来:

x = 3 if (y == 1) else 2 if (y == -1) else 1

虽然在某种程度上,这有点太过分了。

注意,你可以使用if…任何表达式中的Else。例如:

(func1 if y == 1 else func2)(arg1, arg2) 

这里,如果y = 1调用func1,否则调用func2。在这两种情况下,对应的函数将调用参数arg1和arg2。

类似地,以下也成立:

x = (class1 if y == 1 else class2)(arg1, arg2)

其中class1和class2是两个类。

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()

一些内置的收藏夹,map(), reduce()和filter()。所有这些都非常快速和强大。