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!

其他回答

三元运算符

>>> 'ham' if True else 'spam'
'ham'
>>> 'ham' if False else 'spam'
'spam'

这是在2.5中添加的,在此之前你可以使用:

>>> True and 'ham' or 'spam'
'ham'
>>> False and 'ham' or 'spam'
'spam'

然而,如果你想要处理的值被认为是假的,有一个区别:

>>> [] if True else 'spam'
[]
>>> True and [] or 'spam'
'spam'

不是很隐藏,但是函数有属性:

def doNothing():
    pass

doNothing.monkeys = 4
print doNothing.monkeys
4

EVERYTHING是一个对象,因此是可扩展的。我可以将成员变量作为元数据添加到我定义的函数中:

>>> def addInts(x,y): 
...    return x + y
>>> addInts.params = ['integer','integer']
>>> addInts.returnType = 'integer'

这对于编写动态单元测试非常有用,例如。

多行字符串

一种方法是使用反斜杠:

>>> sql = "select * from some_table \
where id > 10"
>>> print sql
select * from some_table where id > 10

另一种是使用三引号:

>>> sql = """select * from some_table 
where id > 10"""
>>> print sql
select * from some_table where id > 10

问题是它们不是缩进的(在代码中看起来很差)。如果你试着缩进,它只会打印你输入的空白。

第三种解决方案,也是我最近发现的,就是把字符串分成几行,然后用圆括号括起来:

>>> sql = ("select * from some_table " # <-- no comma, whitespace at end
           "where id > 10 "
           "order by name") 
>>> print sql
select * from some_table where id > 10 order by name

注意行与行之间没有逗号(这不是一个元组),并且必须考虑字符串需要的任何尾随/前导空格。顺便说一下,所有这些都使用占位符(例如“我的名字是%s”% name)。

如果你在你的应用程序中重命名了一个类,你正在通过Pickle加载用户保存的文件,而其中一个重命名的类存储在用户的旧保存中,你将不能加载这个Pickle文件。

然而,只要在你的类定义中添加一个引用,一切就好了:

例如,:

class Bleh:
    pass

现在,

class Blah:
    pass

所以,你的用户的pickle保存的文件包含一个Bleh的引用,它不存在,由于重命名。这是固定的吗?

Bleh = Blah

简单!