Python编程语言中有哪些鲜为人知但很有用的特性?
尽量将答案限制在Python核心。
每个回答一个特征。
给出一个例子和功能的简短描述,而不仅仅是文档链接。
使用标题作为第一行标记该特性。
快速链接到答案:
参数解包
牙套
链接比较运算符
修饰符
可变默认参数的陷阱/危险
描述符
字典默认的.get值
所以测试
省略切片语法
枚举
其他/
函数作为iter()参数
生成器表达式
导入该
就地值交换
步进列表
__missing__物品
多行正则表达式
命名字符串格式化
嵌套的列表/生成器推导
运行时的新类型
.pth文件
ROT13编码
正则表达式调试
发送到发电机
交互式解释器中的制表符补全
三元表达式
试着/ / else除外
拆包+打印()函数
与声明
元组在for循环、列表推导式和生成器表达式中的解包:
>>> l=[(1,2),(3,4)]
>>> [a+b for a,b in l ]
[3,7]
在这个习语中,用于迭代字典中的(键,数据)对:
d = { 'x':'y', 'f':'e'}
for name, value in d.items(): # one can also use iteritems()
print "name:%s, value:%s" % (name,value)
打印:
name:x, value:y
name:f, value:e
Monkeypatching对象
Python中的每个对象都有__dict__成员,用于存储对象的属性。所以,你可以这样做:
class Foo(object):
def __init__(self, arg1, arg2, **kwargs):
#do stuff with arg1 and arg2
self.__dict__.update(kwargs)
f = Foo('arg1', 'arg2', bar=20, baz=10)
#now f is a Foo object with two extra attributes
可以利用这一点向对象任意添加属性和函数。这也可以用来创建一个快速和肮脏的结构类型。
class struct(object):
def __init__(**kwargs):
self.__dict__.update(kwargs)
s = struct(foo=10, bar=11, baz="i'm a string!')
>>> x=[1,1,2,'a','a',3]
>>> y = [ _x for _x in x if not _x in locals()['_[1]'] ]
>>> y
[1, 2, 'a', 3]
"locals()['_[1]']"是正在创建的列表的"秘密名称"。当正在构建的列表状态影响后续构建决策时非常有用。
元组在for循环、列表推导式和生成器表达式中的解包:
>>> l=[(1,2),(3,4)]
>>> [a+b for a,b in l ]
[3,7]
在这个习语中,用于迭代字典中的(键,数据)对:
d = { 'x':'y', 'f':'e'}
for name, value in d.items(): # one can also use iteritems()
print "name:%s, value:%s" % (name,value)
打印:
name:x, value:y
name:f, value:e
布尔上下文中的对象
空元组、列表、字典、字符串和许多其他对象在布尔上下文中等价于False(非空对象等价于True)。
empty_tuple = ()
empty_list = []
empty_dict = {}
empty_string = ''
empty_set = set()
if empty_tuple or empty_list or empty_dict or empty_string or empty_set:
print 'Never happens!'
这允许逻辑运算返回它的一个操作数,而不是True/False,这在某些情况下很有用:
s = t or "Default value" # s will be assigned "Default value"
# if t is false/empty/none
操作符重载的集合内置:
>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> a | b # Union
{1, 2, 3, 4, 5, 6}
>>> a & b # Intersection
{3, 4}
>>> a < b # Subset
False
>>> a - b # Difference
{1, 2}
>>> a ^ b # Symmetric Difference
{1, 2, 5, 6}
更多详细信息请参阅标准库参考:Set Types