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

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

快速链接到答案:

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


当前回答

我个人很喜欢这三个不同的引语

str = "I'm a string 'but still I can use quotes' inside myself!"
str = """ For some messy multi line strings.
Such as
<html>
<head> ... </head>"""

也很酷:不用转义正则表达式,避免使用原始字符串的可怕的反斜杠沙拉:

str2 = r"\n" 
print str2
>> \n

其他回答

原始字符串中的反斜杠仍然可以转义引号。看到这个:

>>> print repr(r"aaa\"bbb")
'aaa\\"bbb'

注意,反斜杠和双引号都出现在最后的字符串中。

因此,你不能用反斜杠来结束一个原始字符串:

>>> print repr(r"C:\")
SyntaxError: EOL while scanning string literal
>>> print repr(r"C:\"")
'C:\\"'

这是因为实现原始字符串是为了帮助编写正则表达式,而不是为了编写Windows路径。在Gotcha - Windows文件名中的反斜杠上阅读关于这个的长讨论。

猜测整数基数

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

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

def doNothing():
    pass

doNothing.monkeys = 4
print doNothing.monkeys
4

功能的支持。

特别是生成器和生成器表达式。

Ruby使它再次成为主流,但Python也可以做得一样好。在库中不像Ruby中那样普遍,这太糟糕了,但我更喜欢它的语法,它更简单。

因为它们不是那么普遍,我没有看到很多例子来说明它们为什么有用,但它们让我写出了更干净、更高效的代码。

绝密属性

>>> class A(object): pass
>>> a = A()
>>> setattr(a, "can't touch this", 123)
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', "can't touch this"]
>>> a.can't touch this # duh
  File "<stdin>", line 1
    a.can't touch this
                     ^
SyntaxError: EOL while scanning string literal
>>> getattr(a, "can't touch this")
123
>>> setattr(a, "__class__.__name__", ":O")
>>> a.__class__.__name__
'A'
>>> getattr(a, "__class__.__name__")
':O'