Python编程语言中有哪些鲜为人知但很有用的特性?
尽量将答案限制在Python核心。
每个回答一个特征。
给出一个例子和功能的简短描述,而不仅仅是文档链接。
使用标题作为第一行标记该特性。
快速链接到答案:
参数解包
牙套
链接比较运算符
修饰符
可变默认参数的陷阱/危险
描述符
字典默认的.get值
所以测试
省略切片语法
枚举
其他/
函数作为iter()参数
生成器表达式
导入该
就地值交换
步进列表
__missing__物品
多行正则表达式
命名字符串格式化
嵌套的列表/生成器推导
运行时的新类型
.pth文件
ROT13编码
正则表达式调试
发送到发电机
交互式解释器中的制表符补全
三元表达式
试着/ / else除外
拆包+打印()函数
与声明
很多人不知道dir函数。这是一种很好的方法,可以从解释器中找出对象可以做什么。例如,如果你想查看所有字符串方法的列表:
>>> dir("foo")
['__add__', '__class__', '__contains__', (snipped a bunch), 'title',
'translate', 'upper', 'zfill']
然后,如果你想要关于某个方法的更多信息,你可以在它上面调用“help”。
>>> help("foo".upper)
Help on built-in function upper:
upper(...)
S.upper() -> string
Return a copy of the string S converted to uppercase.
threading.enumerate()提供了对系统中所有Thread对象的访问,sys._current_frames()返回系统中所有线程的当前堆栈帧,因此将这两者结合起来,你会得到Java风格的堆栈转储:
def dumpstacks(signal, frame):
id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print "\n".join(code)
import signal
signal.signal(signal.SIGQUIT, dumpstacks)
在多线程python程序开始时执行此操作,您可以通过发送SIGQUIT随时访问线程的当前状态。你也可以选择信号。SIGUSR1或signal。sigusr2。
See
迭代工具
这个模块经常被忽视。下面的例子使用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。
操纵sys.modules
你可以直接操作模块缓存,使模块可用或不可用,如你所愿:
>>> import sys
>>> import ham
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named ham
# Make the 'ham' module available -- as a non-module object even!
>>> sys.modules['ham'] = 'ham, eggs, saussages and spam.'
>>> import ham
>>> ham
'ham, eggs, saussages and spam.'
# Now remove it again.
>>> sys.modules['ham'] = None
>>> import ham
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named ham
这甚至适用于可用的模块,在某种程度上也适用于已经导入的模块:
>>> import os
# Stop future imports of 'os'.
>>> sys.modules['os'] = None
>>> import os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named os
# Our old imported module is still available.
>>> os
<module 'os' from '/usr/lib/python2.5/os.pyc'>
如最后一行所示,更改sys.;模块只影响将来的导入语句,而不影响过去的导入语句,所以如果你想影响其他模块,在给它们尝试导入模块的机会之前进行这些更改是很重要的——通常是在导入它们之前。None是sys中的一个特殊值。模块,用于负缓存(表明该模块第一次没有找到,因此没有必要再次查找)。任何其他值都将是导入操作的结果——即使它不是模块对象。您可以使用它将模块替换为与您想要的行为完全一致的对象。删除sys. exe表项。Modules完全导致下一次导入对该模块进行正常搜索,即使之前已经导入了该模块。
对象实例的方法替换
您可以替换已经创建的对象实例的方法。它允许你创建具有不同(例外)功能的对象实例:
>>> class C(object):
... def fun(self):
... print "C.a", self
...
>>> inst = C()
>>> inst.fun() # C.a method is executed
C.a <__main__.C object at 0x00AE74D0>
>>> instancemethod = type(C.fun)
>>>
>>> def fun2(self):
... print "fun2", self
...
>>> inst.fun = instancemethod(fun2, inst, C) # Now we are replace C.a by fun2
>>> inst.fun() # ... and fun2 is executed
fun2 <__main__.C object at 0x00AE74D0>
C.a在inst实例中被fun2()取代(self没有改变)。
或者,我们也可以使用new模块,但它自Python 2.6起就被贬低了:
>>> def fun3(self):
... print "fun3", self
...
>>> import new
>>> inst.fun = new.instancemethod(fun3, inst, C)
>>> inst.fun()
fun3 <__main__.C object at 0x00AE74D0>
节点:这个解决方案不应该被用作继承机制的一般替代!但在某些特定的情况下(调试、模拟),它可能非常方便。
警告:此解决方案不适用于内置类型和使用插槽的新样式类。