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

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

快速链接到答案:

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


当前回答

for line in open('foo'):
    print(line)

这相当于(但更好):

f = open('foo', 'r')
for line in f.readlines():
   print(line)
f.close()

其他回答

对象数据模型

您可以为自己的类重写语言中的任何操作符。有关完整列表,请参阅本页。一些例子:

您可以重写任何运算符(* + - // / % ^ == < > <= >=。等等)。所有这些都是通过重写对象中的__mul__, __add__等来实现的。你甚至可以重写像__rmul__这样的东西来分别处理your_object*something_else和something_else*your_object.。是属性访问(a.b),并且可以通过使用__getattr__来重写以处理任意b。这里还包括一个使用__call__的(…)。 您可以创建自己的slice语法(a[stuff]),这可能非常复杂,与列表中使用的标准语法完全不同(numpy在其数组中有一个很好的例子,说明了这种功能的强大),使用您喜欢的、、:和…的任何组合,使用slice对象。 特别处理语言中许多关键字所发生的情况。包括del、in、import和not。 处理与对象一起调用许多内置函数时发生的情况。标准的__int__, __str__等会在这里,但__len__, __reversed__, __abs__和三个参数__pow__(用于模取幂)也会在这里。

字符串转义和unicode转义编码

假设你有一个来自外部源的字符串,它包含\n, \t等等。如何将它们转换为换行或制表?只需使用字符串转义编码解码字符串!

>>> print s
Hello\nStack\toverflow
>>> print s.decode('string-escape')
Hello
Stack   overflow

另一个问题。你有普通的unicode字符串,比如\u01245。如何让它起作用?只是解码字符串使用unicode转义编码!

>>> s = '\u041f\u0440\u0438\u0432\u0456\u0442, \u0441\u0432\u0456\u0442!'
>>> print s
\u041f\u0440\u0438\u0432\u0456\u0442, \u0441\u0432\u0456\u0442!
>>> print unicode(s)
\u041f\u0440\u0438\u0432\u0456\u0442, \u0441\u0432\u0456\u0442!
>>> print unicode(s, 'unicode-escape')
Привіт, світ!

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

scanner类。http://code.activestate.com/recipes/457664-hidden-scanner-functionality-in-re-module/

这里有2个彩蛋:


python本身的一个:

>>> import __hello__
Hello world...

另一个是在Werkzeug模块中,它有点复杂,在这里:

通过查看Werkzeug的源代码,在Werkzeug /__init__.py中,有一行应该引起你的注意:

'werkzeug._internal':   ['_easteregg']

如果你有点好奇,这应该让你看看werkzeug/_internal.py,在那里,你会发现一个_easteregg()函数,它在参数中接受一个wsgi应用程序,它还包含一些base64编码的数据和2个嵌套的函数,如果在查询字符串中找到一个名为macgybarchakku的参数,它似乎做了一些特殊的事情。

因此,为了揭示这个彩蛋,似乎你需要在_easteregg()函数中包装一个应用程序,让我们开始:

from werkzeug import Request, Response, run_simple
from werkzeug import _easteregg

@Request.application
def application(request):
    return Response('Hello World!')

run_simple('localhost', 8080, _easteregg(application))

现在,如果你运行应用程序并访问http://localhost:8080/?macgybarchakku,你应该会看到彩蛋。