Python编程语言中有哪些鲜为人知但很有用的特性?
尽量将答案限制在Python核心。
每个回答一个特征。
给出一个例子和功能的简短描述,而不仅仅是文档链接。
使用标题作为第一行标记该特性。
快速链接到答案:
参数解包
牙套
链接比较运算符
修饰符
可变默认参数的陷阱/危险
描述符
字典默认的.get值
所以测试
省略切片语法
枚举
其他/
函数作为iter()参数
生成器表达式
导入该
就地值交换
步进列表
__missing__物品
多行正则表达式
命名字符串格式化
嵌套的列表/生成器推导
运行时的新类型
.pth文件
ROT13编码
正则表达式调试
发送到发电机
交互式解释器中的制表符补全
三元表达式
试着/ / else除外
拆包+打印()函数
与声明
不是“隐藏”,而是很有用,不常用
像这样快速创建字符串连接函数
comma_join = ",".join
semi_join = ";".join
print comma_join(["foo","bar","baz"])
'foo,bar,baz
and
能够更优雅地创建字符串列表,而不是引号,逗号混乱。
l = ["item1", "item2", "item3"]
取而代之的是
l = "item1 item2 item3".split()
Python的高级切片操作有一个鲜为人知的语法元素,即省略号:
>>> class C(object):
... def __getitem__(self, item):
... return item
...
>>> C()[1:2, ..., 3]
(slice(1, 2, None), Ellipsis, 3)
不幸的是,它几乎没有什么用处,因为只有在涉及元组时才支持省略号。
内置方法或函数不实现描述符协议,这使得不可能做这样的事情:
>>> class C(object):
... id = id
...
>>> C().id()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: id() takes exactly one argument (0 given)
然而,你可以创建一个小的绑定描述符来实现这一点:
>>> from types import MethodType
>>> class bind(object):
... def __init__(self, callable):
... self.callable = callable
... def __get__(self, obj, type=None):
... if obj is None:
... return self
... return MethodType(self.callable, obj, type)
...
>>> class C(object):
... id = bind(id)
...
>>> C().id()
7414064
命名格式
% -formatting接受字典(也应用%i/%s等验证)。
>>> print "The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42}
The answer is 42.
>>> foo, bar = 'question', 123
>>> print "The %(foo)s is %(bar)i." % locals()
The question is 123.
由于locals()也是一个字典,您可以简单地将其作为字典传递,并从局部变量中获得% -替换。我认为这是不受欢迎的,但简化了事情。
新的样式格式
>>> print("The {foo} is {bar}".format(foo='answer', bar=42))