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

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

快速链接到答案:

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


当前回答

很明显,反重力模块。 xkcd # 353

其他回答

不是编程特性,但在使用Python和bash或shell脚本时很有用。

python -c"import os; print(os.getcwd());"

请参阅此处的python文档。在编写较长的Python脚本时需要注意的其他事项可以在本讨论中看到。

操作符可以作为函数调用:

from operator import add
print reduce(add, [1,2,3,4,5,6])

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

Getattr接受第三个参数

Getattr (obj, attribute_name, default)是这样的:

try:
    return obj.attribute
except AttributeError:
    return default

只不过attribute_name可以是任何字符串。

这对于鸭子输入非常有用。也许你有这样的东西:

class MyThing:
    pass
class MyOtherThing:
    pass
if isinstance(obj, (MyThing, MyOtherThing)):
    process(obj)

(顺便说一下,isinstance(obj, (a,b))表示isinstance(obj, a)或isinstance(obj, b)。)

当你创建一种新的东西时,你需要把它添加到它出现的任何地方。(这种结构在重新加载模块或以两个名称导入同一个文件时也会导致问题。这种事情发生的次数比人们愿意承认的要多。)但是你可以说:

class MyThing:
    processable = True
class MyOtherThing:
    processable = True
if getattr(obj, 'processable', False):
    process(obj)

添加继承就更好了:所有可处理对象的示例都可以继承

class Processable:
    processable = True

但你不需要说服每个人都继承你的基类,只需要设置一个属性。

每次打印一屏多行字符串

没有真正有用的功能隐藏在网站。_Printer类,其license对象是一个实例。调用后者时,打印Python许可证。可以创建另一个相同类型的对象,传递一个字符串——例如文件的内容——作为第二个参数,并调用它:

type(license)(0,open('textfile.txt').read(),0)()

这将打印一次按一定行数分割的文件内容:

...
file row 21
file row 22
file row 23

Hit Return for more, or q (and Return) to quit: