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

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

快速链接到答案:

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


当前回答

对象实例的方法替换

您可以替换已经创建的对象实例的方法。它允许你创建具有不同(例外)功能的对象实例:

>>> 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>

节点:这个解决方案不应该被用作继承机制的一般替代!但在某些特定的情况下(调试、模拟),它可能非常方便。

警告:此解决方案不适用于内置类型和使用插槽的新样式类。

其他回答

模块导出命名空间中的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__ =的好理由。

下面是我在调试类型错误时使用的一个有用的函数

def typePrint(object):
    print(str(object) + " - (" + str(type(object)) + ")")

例如,它只是打印输入后跟类型

>>> a = 101
>>> typePrint(a)
    101 - (<type 'int'>)

集理解

>>> {i**2 for i in range(5)}                                                       
set([0, 1, 4, 16, 9])

Python文档

维基百科的条目

虽然不是很python化,但可以使用print来写入文件

打印>>outFile, 'I am Being Written'

解释:

这种形式有时被称为 “打印雪佛龙。”在这种形式中, 第一个表达式>后>必须 求值为“类文件”对象, 具体来说,一个对象具有 如上所述编写()方法。 有了这个扩展形式, 随后的表达式被打印到 这个文件对象。如果第一个 表达式的值为None sys。的文件使用Stdout 输出。

我不确定这在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,因为它是一个有效的标识符名称)。