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

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

快速链接到答案:

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


当前回答

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

其他回答

如果在函数中使用exec,变量查找规则将发生巨大变化。闭包不再可能,但Python允许在函数中使用任意标识符。这为您提供了一个“可修改的locals()”,并可用于星型导入标识符。缺点是,它会使每次查找都变慢,因为变量最终会在字典中而不是在帧中的槽中结束:

>>> def f():
...  exec "a = 42"
...  return a
... 
>>> def g():
...  a = 42
...  return a
... 
>>> import dis
>>> dis.dis(f)
  2           0 LOAD_CONST               1 ('a = 42')
              3 LOAD_CONST               0 (None)
              6 DUP_TOP             
              7 EXEC_STMT           

  3           8 LOAD_NAME                0 (a)
             11 RETURN_VALUE        
>>> dis.dis(g)
  2           0 LOAD_CONST               1 (42)
              3 STORE_FAST               0 (a)

  3           6 LOAD_FAST                0 (a)
              9 RETURN_VALUE        

Re可以调用函数!

事实上,您可以在每次匹配正则表达式时调用函数,这非常方便。 这里我有一个例子,把每个“Hello”替换为“Hi”,把“there”替换为“Fred”,等等。

import re

def Main(haystack):
  # List of from replacements, can be a regex
  finds = ('Hello', 'there', 'Bob')
  replaces = ('Hi,', 'Fred,', 'how are you?')

  def ReplaceFunction(matchobj):
    for found, rep in zip(matchobj.groups(), replaces):
      if found != None:
        return rep

    # log error
    return matchobj.group(0)

  named_groups = [ '(%s)' % find for find in finds ]
  ret = re.sub('|'.join(named_groups), ReplaceFunction, haystack)
  print ret

if __name__ == '__main__':
  str = 'Hello there Bob'
  Main(str)
  # Prints 'Hi, Fred, how are you?'

Namedtuple是一个元组

>>> node = namedtuple('node', "a b")
>>> node(1,2) + node(5,6)
(1, 2, 5, 6)
>>> (node(1,2), node(5,6))
(node(a=1, b=2), node(a=5, b=6))
>>> 

更多的实验来回应评论:

>>> from collections import namedtuple
>>> from operator import *
>>> mytuple = namedtuple('A', "a b")
>>> yourtuple = namedtuple('Z', "x y")
>>> mytuple(1,2) + yourtuple(5,6)
(1, 2, 5, 6)
>>> q = [mytuple(1,2), yourtuple(5,6)]
>>> q
[A(a=1, b=2), Z(x=5, y=6)]
>>> reduce(operator.__add__, q)
(1, 2, 5, 6)

namedtuple是tuple的一个有趣的子类型。

条件赋值

x = 3 if (y == 1) else 2

正如它听起来的那样:“如果y是1,则赋3给x,否则赋2给x”。注意,括号不是必需的,但是为了可读性,我喜欢它们。如果你有更复杂的东西,你也可以把它串起来:

x = 3 if (y == 1) else 2 if (y == -1) else 1

虽然在某种程度上,这有点太过分了。

注意,你可以使用if…任何表达式中的Else。例如:

(func1 if y == 1 else func2)(arg1, arg2) 

这里,如果y = 1调用func1,否则调用func2。在这两种情况下,对应的函数将调用参数arg1和arg2。

类似地,以下也成立:

x = (class1 if y == 1 else class2)(arg1, arg2)

其中class1和class2是两个类。

在子类中扩展属性(定义为描述符)

有时扩展(修改)子类中描述符“返回”的值是有用的。使用super()可以轻松完成:

class A(object):
    @property
    def prop(self):
        return {'a': 1}

class B(A):
    @property
    def prop(self):
        return dict(super(B, self).prop, b=2)

将其存储在test.py中并运行python -i test.py(另一个隐藏特性:-i选项执行脚本并允许您以交互模式继续):

>>> B().prop
{'a': 1, 'b': 2}