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

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

快速链接到答案:

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


当前回答

commands.getoutput

如果你想获得直接输出到stdout或stderr的函数的输出,就像os的情况一样。系统命令。Getoutput来拯救。整个模块都非常棒。

>>> print commands.getoutput('ls')
myFile1.txt    myFile2.txt    myFile3.txt    myFile4.txt    myFile5.txt
myFile6.txt    myFile7.txt    myFile8.txt    myFile9.txt    myFile10.txt
myFile11.txt   myFile12.txt   myFile13.txt   myFile14.txt   module.py

其他回答

关于Nick Johnson的Property类的实现(只是描述符的演示,当然,不是内置的替换),我将包括一个引发AttributeError的setter:

class Property(object):
    def __init__(self, fget):
        self.fget = fget

    def __get__(self, obj, type):
        if obj is None:
            return self
        return self.fget(obj)

    def __set__(self, obj, value):
       raise AttributeError, 'Read-only attribute'

包含setter使其成为数据描述符,而不是方法/非数据描述符。数据描述符优先于实例字典。现在,实例不能将不同的对象赋值给属性名,并且尝试将其赋值给属性将引发属性错误。

创建生成器对象

如果你写

x=(n for n in foo if bar(n))

你可以取出生成器,把它赋值给x,这意味着你可以这样做

for n in x:

这样做的优点是不需要中间存储,如果需要中间存储,则需要中间存储

x = [n for n in foo if bar(n)]

在某些情况下,这可以显著提高速度。

你可以在生成器的末尾附加许多if语句,基本上复制嵌套的for循环:

>>> n = ((a,b) for a in range(0,2) for b in range(4,6))
>>> for i in n:
...   print i 

(0, 4)
(0, 5)
(1, 4)
(1, 5)

猜测整数基数

>>> int('10', 0)
10
>>> int('0x10', 0)
16
>>> int('010', 0)  # does not work on Python 3.x
8
>>> int('0o10', 0)  # Python >=2.6 and Python 3.x
8
>>> int('0b10', 0)  # Python >=2.6 and Python 3.x
2

创建具有相关数据的两个序列的字典

In [15]: t1 = (1, 2, 3)

In [16]: t2 = (4, 5, 6)

In [17]: dict (zip(t1,t2))
Out[17]: {1: 4, 2: 5, 3: 6}

一个词:IPython

标签内省,漂亮的打印,%调试,历史管理,pylab,…值得花时间好好学习。