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

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

快速链接到答案:

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


当前回答

激活IDE中接受它的自动完成(如IDLE, Editra, IEP),而不是做: “嗨”。(然后你按TAB键),你可以在IDE中作弊,只是制造 嗨。”(你可以看到,在开始的时候没有单引号)因为它只会跟着最新的标点符号,就像当你添加:并按enter,它直接添加了一个缩进,不知道它是否会改变,但它不再是一个提示:)

其他回答

模块导出命名空间中的EVERYTHING

包括从其他模块导入的名称!

# this is "answer42.py"
from operator import *
from inspect  import *

现在测试模块中可导入的内容。

>>> import answer42
>>> answer42.__dict__.keys()
['gt', 'imul', 'ge', 'setslice', 'ArgInfo', 'getfile', 'isCallable', 'getsourcelines', 'CO_OPTIMIZED', 'le', 're', 'isgenerator', 'ArgSpec', 'imp', 'lt', 'delslice', 'BlockFinder', 'getargspec', 'currentframe', 'CO_NOFREE', 'namedtuple', 'rshift', 'string', 'getframeinfo', '__file__', 'strseq', 'iconcat', 'getmro', 'mod', 'getcallargs', 'isub', 'getouterframes', 'isdatadescriptor', 'modulesbyfile', 'setitem', 'truth', 'Attribute', 'div', 'CO_NESTED', 'ixor', 'getargvalues', 'ismemberdescriptor', 'getsource', 'isMappingType', 'eq', 'index', 'xor', 'sub', 'getcomments', 'neg', 'getslice', 'isframe', '__builtins__', 'abs', 'getmembers', 'mul', 'getclasstree', 'irepeat', 'is_', 'getitem', 'indexOf', 'Traceback', 'findsource', 'ModuleInfo', 'ipow', 'TPFLAGS_IS_ABSTRACT', 'or_', 'joinseq', 'is_not', 'itruediv', 'getsourcefile', 'dis', 'os', 'iand', 'countOf', 'getinnerframes', 'pow', 'pos', 'and_', 'lshift', '__name__', 'sequenceIncludes', 'isabstract', 'isbuiltin', 'invert', 'contains', 'add', 'isSequenceType', 'irshift', 'types', 'tokenize', 'isfunction', 'not_', 'istraceback', 'getmoduleinfo', 'isgeneratorfunction', 'getargs', 'CO_GENERATOR', 'cleandoc', 'classify_class_attrs', 'EndOfBlock', 'walktree', '__doc__', 'getmodule', 'isNumberType', 'ilshift', 'ismethod', 'ifloordiv', 'formatargvalues', 'indentsize', 'getmodulename', 'inv', 'Arguments', 'iscode', 'CO_NEWLOCALS', 'formatargspec', 'iadd', 'getlineno', 'imod', 'CO_VARKEYWORDS', 'ne', 'idiv', '__package__', 'CO_VARARGS', 'attrgetter', 'methodcaller', 'truediv', 'repeat', 'trace', 'isclass', 'ior', 'ismethoddescriptor', 'sys', 'isroutine', 'delitem', 'stack', 'concat', 'getdoc', 'getabsfile', 'ismodule', 'linecache', 'floordiv', 'isgetsetdescriptor', 'itemgetter', 'getblock']
>>> from answer42 import getmembers
>>> getmembers
<function getmembers at 0xb74b2924>
>>> 

这是一个不从x import *并定义__all__ =的好理由。

用sum()扁平化列表。

sum()内置函数可用于将__add__个列表放在一起,提供了一种方便的方法来将列表的列表扁平化:

Python 2.7.1 (r271:86832, May 27 2011, 21:41:45) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

除了haridsv之前提到的这一点之外:

>>> foo = bar = baz = 1
>>> foo, bar, baz
(1, 1, 1)

也可以这样做:

>>> foo, bar, baz = 1, 2, 3
>>> foo, bar, baz
(1, 2, 3)

commands.getoutput

如果你想获得直接输出到stdout或stderr的函数的输出,就像os的情况一样。系统命令。Getoutput来拯救。整个模块都非常棒。

>>> print commands.getoutput('ls')
myFile1.txt    myFile2.txt    myFile3.txt    myFile4.txt    myFile5.txt
myFile6.txt    myFile7.txt    myFile8.txt    myFile9.txt    myFile10.txt
myFile11.txt   myFile12.txt   myFile13.txt   myFile14.txt   module.py

我不确定这在Python文档中的位置(或是否),但对于Python 2。x(至少2.5和2.6,我刚刚尝试过),打印语句可以用括号调用。如果您希望能够轻松地移植一些Python 2,这可能很有用。Python 3.x代码。

例子: 我们想要Moshiach Now在python 2.5, 2.6和3.x中工作。

此外,在Python 2和3中,not操作符可以用括号调用: 不是假的 而且 (假) 都应该返回True。

括号也可以用于其他语句和操作符。

编辑:把括号放在非操作符(可能是任何其他操作符)周围不是一个好主意,因为它会导致令人惊讶的情况,就像这样(发生这种情况是因为括号实际上只是在1周围):

>>> (not 1) == 9
False

>>> not(1) == 9
True

这也可以工作,对于某些值(我认为它不是一个有效的标识符名称),像这样: not'val'将返回False, print'We want Moshiach Now'将返回We want Moshiach Now。(但是not552会引发NameError,因为它是一个有效的标识符名称)。