Python编程语言中有哪些鲜为人知但很有用的特性?
尽量将答案限制在Python核心。
每个回答一个特征。
给出一个例子和功能的简短描述,而不仅仅是文档链接。
使用标题作为第一行标记该特性。
快速链接到答案:
参数解包
牙套
链接比较运算符
修饰符
可变默认参数的陷阱/危险
描述符
字典默认的.get值
所以测试
省略切片语法
枚举
其他/
函数作为iter()参数
生成器表达式
导入该
就地值交换
步进列表
__missing__物品
多行正则表达式
命名字符串格式化
嵌套的列表/生成器推导
运行时的新类型
.pth文件
ROT13编码
正则表达式调试
发送到发电机
交互式解释器中的制表符补全
三元表达式
试着/ / else除外
拆包+打印()函数
与声明
迭代工具
这个模块经常被忽视。下面的例子使用itertools.chain()
扁平化列表:
>>> from itertools import *
>>> l = [[1, 2], [3, 4]]
>>> list(chain(*l))
[1, 2, 3, 4]
更多应用请参见http://docs.python.org/library/itertools.html#recipes。
Python sort函数正确地对元组排序(即使用熟悉的字典顺序):
a = [(2, "b"), (1, "a"), (2, "a"), (3, "c")]
print sorted(a)
#[(1, 'a'), (2, 'a'), (2, 'b'), (3, 'c')]
如果您想先按年龄再按姓名对人员列表进行排序,则非常有用。
...dict.get()有一个默认值None,从而避免KeyErrors:
In [1]: test = { 1 : 'a' }
In [2]: test[2]
---------------------------------------------------------------------------
<type 'exceptions.KeyError'> Traceback (most recent call last)
<ipython console> in <module>()
<type 'exceptions.KeyError'>: 2
In [3]: test.get( 2 )
In [4]: test.get( 1 )
Out[4]: 'a'
In [5]: test.get( 2 ) == None
Out[5]: True
甚至在“现场”指定这个:
In [6]: test.get( 2, 'Some' ) == 'Some'
Out[6]: True
你可以使用setdefault()来设置一个值,如果它不存在就返回:
>>> a = {}
>>> b = a.setdefault('foo', 'bar')
>>> a
{'foo': 'bar'}
>>> b
'bar
可以使用属性使类接口更加严格。
class C(object):
def __init__(self, foo, bar):
self.foo = foo # read-write property
self.bar = bar # simple attribute
def _set_foo(self, value):
self._foo = value
def _get_foo(self):
return self._foo
def _del_foo(self):
del self._foo
# any of fget, fset, fdel and doc are optional,
# so you can make a write-only and/or delete-only property.
foo = property(fget = _get_foo, fset = _set_foo,
fdel = _del_foo, doc = 'Hello, I am foo!')
class D(C):
def _get_foo(self):
return self._foo * 2
def _set_foo(self, value):
self._foo = value / 2
foo = property(fget = _get_foo, fset = _set_foo,
fdel = C.foo.fdel, doc = C.foo.__doc__)
在Python 2.6和3.0中:
class C(object):
def __init__(self, foo, bar):
self.foo = foo # read-write property
self.bar = bar # simple attribute
@property
def foo(self):
'''Hello, I am foo!'''
return self._foo
@foo.setter
def foo(self, value):
self._foo = value
@foo.deleter
def foo(self):
del self._foo
class D(C):
@C.foo.getter
def foo(self):
return self._foo * 2
@foo.setter
def foo(self, value):
self._foo = value / 2
要了解属性如何工作的更多信息,请参阅描述符。