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

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

快速链接到答案:

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


当前回答

Python的禅宗

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

其他回答

reversed()内置。在很多情况下,它使得迭代更加简洁。

简单的例子:

for i in reversed([1, 2, 3]):
    print(i)

生产:

3
2
1

然而,reversed()也适用于任意迭代器,例如文件中的行或生成器表达式。

能够替换甚至像文件删除,文件打开等-语言库的直接操作。这在测试时是一个巨大的优势。你不必把所有东西都包装在复杂的容器里。只需要替换一个函数/方法就可以了。这也被称为猴子修补。

切片和可变性

复制清单

>>> x = [1,2,3]
>>> y = x[:]
>>> y.pop()
3
>>> y
[1, 2]
>>> x
[1, 2, 3]

替换列表

>>> x = [1,2,3]
>>> y = x
>>> y[:] = [4,5,6]
>>> x
[4, 5, 6]

重新加载模块可以实现“实时编码”风格。但是类实例不更新。以下是原因,以及如何解决这个问题。记住,所有东西,是的,所有东西都是一个对象。

>>> from a_package import a_module
>>> cls = a_module.SomeClass
>>> obj = cls()
>>> obj.method()
(old method output)

现在更改a_module.py中的方法,并希望更新对象。

>>> reload(a_module)
>>> a_module.SomeClass is cls
False # Because it just got freshly created by reload.
>>> obj.method()
(old method output)

这里有一种更新方法(但考虑使用剪刀运行):

>>> obj.__class__ is cls
True # it's the old class object
>>> obj.__class__ = a_module.SomeClass # pick up the new class
>>> obj.method()
(new method output)

这是“剪刀式运行”,因为对象的内部状态可能与新类所期望的不同。这适用于非常简单的情况,但除此之外,pickle是您的朋友。尽管如此,理解为什么这是有效的仍然是有帮助的。

使用and和or来模拟第三运算符。

python中的and和or操作符返回对象本身,而不是布尔值。因此:

In [18]: a = True

In [19]: a and 3 or 4
Out[19]: 3

In [20]: a = False

In [21]: a and 3 or 4
Out[21]: 4

然而,Py 2.5似乎添加了一个显式的第三运算符

    In [22]: a = 5 if True else '6'

    In [23]: a
    Out[23]: 5

好吧,如果你确定你的true子句的结果不是False,这是可行的。例子:

>>> def foo(): 
...     print "foo"
...     return 0
...
>>> def bar(): 
...     print "bar"
...     return 1
...
>>> 1 and foo() or bar()
foo
bar
1

要做到这一点,你还需要多做一点:

>>> (1 and [foo()] or [bar()])[0]
foo
0

然而,这并不漂亮。如果你的python版本支持它,请使用条件操作符。

>>> foo() if True or bar()
foo
0