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

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

快速链接到答案:

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


当前回答

绝密属性

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

其他回答

Python可以理解任何类型的unicode数字,而不仅仅是ASCII类型:

>>> s = u'10585'
>>> s
u'\uff11\uff10\uff15\uff18\uff15'
>>> print s
10585
>>> int(s)
10585
>>> float(s)
10585.0

内置base64, zlib和rot13编解码器

字符串有编码和解码方法。通常这用于将str转换为unicode,反之亦然,例如u = s.c encode('utf8')。但还有其他一些方便的内置编解码器。使用zlib(和bz2)进行压缩和解压,无需显式导入:

>>> s = 'a' * 100
>>> s.encode('zlib')
'x\x9cKL\xa4=\x00\x00zG%\xe5'

类似地,你可以编码和解码base64:

>>> 'Hello world'.encode('base64')
'SGVsbG8gd29ybGQ=\n'
>>> 'SGVsbG8gd29ybGQ=\n'.decode('base64')
'Hello world'

当然,你也可以:

>>> 'Secret message'.encode('rot13')
'Frperg zrffntr'

Python的高级切片操作有一个鲜为人知的语法元素,即省略号:

>>> class C(object):
...  def __getitem__(self, item):
...   return item
... 
>>> C()[1:2, ..., 3]
(slice(1, 2, None), Ellipsis, 3)

不幸的是,它几乎没有什么用处,因为只有在涉及元组时才支持省略号。

切片运算符中的step参数。例如:

a = [1,2,3,4,5]
>>> a[::2]  # iterate over the whole list in 2-increments
[1,3,5]

特殊情况x[::-1]是“x反转”的有用习语。

>>> a[::-1]
[5,4,3,2,1]

python成语x =…如果……其他的……远优于x =…和…还是……原因如下:

尽管声明

x = 3 if (y == 1) else 2

等于

x = y == 1 and 3 or 2

如果使用x =…和…还是……成语,有一天你可能会被这种棘手的情况所困扰:

x = 0 if True else 1    # sets x equal to 0

因此不等于

x = True and 0 or 1   # sets x equal to 1

要了解更多正确的方法, 参见Python的隐藏特性。