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

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

快速链接到答案:

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


当前回答

在子类中扩展属性(定义为描述符)

有时扩展(修改)子类中描述符“返回”的值是有用的。使用super()可以轻松完成:

class A(object):
    @property
    def prop(self):
        return {'a': 1}

class B(A):
    @property
    def prop(self):
        return dict(super(B, self).prop, b=2)

将其存储在test.py中并运行python -i test.py(另一个隐藏特性:-i选项执行脚本并允许您以交互模式继续):

>>> B().prop
{'a': 1, 'b': 2}

其他回答

元组在for循环、列表推导式和生成器表达式中的解包:

>>> l=[(1,2),(3,4)]
>>> [a+b for a,b in l ] 
[3,7]

在这个习语中,用于迭代字典中的(键,数据)对:

d = { 'x':'y', 'f':'e'}
for name, value in d.items():  # one can also use iteritems()
   print "name:%s, value:%s" % (name,value)

打印:

name:x, value:y
name:f, value:e

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

字典有一个get()方法

字典有一个'get()'方法。如果你执行d['key']而key不存在,你会得到一个异常。如果执行d.t get('key'),如果'key'不存在,则返回None。您可以添加第二个参数来返回该项,而不是None,例如:d.t get('key', 0)。

它非常适合做数字相加这样的事情:

Sum [value] = Sum。Get (value, 0) + 1

在列表推导式中交错if和for

>>> [(x, y) for x in range(4) if x % 2 == 1 for y in range(4)]
[(1, 0), (1, 1), (1, 2), (1, 3), (3, 0), (3, 1), (3, 2), (3, 3)]

直到我学了哈斯克尔,我才意识到这一点。

元组拆包:

>>> (a, (b, c), d) = [(1, 2), (3, 4), (5, 6)]
>>> a
(1, 2)
>>> b
3
>>> c, d
(4, (5, 6))

更模糊的是,你可以在函数参数中做到这一点(在Python 2.x中;Python 3。X将不再允许这样):

>>> def addpoints((x1, y1), (x2, y2)):
...     return (x1+x2, y1+y2)
>>> addpoints((5, 0), (3, 5))
(8, 5)