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

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

快速链接到答案:

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


当前回答

Python的禅宗

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

其他回答

一切事物的一等性(“一切事物都是一个物体”),以及这可能造成的混乱。

>>> x = 5
>>> y = 10
>>> 
>>> def sq(x):
...   return x * x
... 
>>> def plus(x):
...   return x + x
... 
>>> (sq,plus)[y>x](y)
20

最后一行创建一个包含这两个函数的元组,然后计算y>x (True)并将其作为元组的索引(通过将其强制转换为int类型,1),然后使用参数y调用该函数并显示结果。

对于进一步的滥用,如果你返回一个带索引的对象(例如一个列表),你可以在末尾添加更多的方括号;如果内容是可调用的,更多的括号,等等。为了更变态,使用这样的代码的结果作为另一个例子中的表达式(即用下面的代码替换y>x):

(sq,plus)[y>x](y)[4](x)

这展示了Python的两个方面——极端的“一切都是一个对象”哲学,以及不恰当或考虑不良的语言语法使用方法,可能导致完全不可读、不可维护的意大利面条代码,适合一个表达式。

将元组传递给内置函数

很多Python函数接受元组,但看起来并不像。例如,你想测试你的变量是否是一个数字,你可以这样做:

if isinstance (number, float) or isinstance (number, int):  
   print "yaay"

但如果你传递给我们元组,这看起来更干净:

if isinstance (number, (float, int)):  
   print "yaay"

类作为一级对象(通过动态类定义显示)

还要注意闭包的使用。如果这个例子看起来是解决问题的“正确”方法,请仔细考虑……好几次:)

def makeMeANewClass(parent, value):
  class IAmAnObjectToo(parent):
    def theValue(self):
      return value
  return IAmAnObjectToo

Klass = makeMeANewClass(str, "fred")
o = Klass()
print isinstance(o, str)  # => True
print o.theValue()        # => fred

threading.enumerate()提供了对系统中所有Thread对象的访问,sys._current_frames()返回系统中所有线程的当前堆栈帧,因此将这两者结合起来,你会得到Java风格的堆栈转储:

def dumpstacks(signal, frame):
    id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
    code = []
    for threadId, stack in sys._current_frames().items():
        code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
    print "\n".join(code)

import signal
signal.signal(signal.SIGQUIT, dumpstacks)

在多线程python程序开始时执行此操作,您可以通过发送SIGQUIT随时访问线程的当前状态。你也可以选择信号。SIGUSR1或signal。sigusr2。

See

使用负step反转可迭代对象

>>> s = "Hello World"
>>> s[::-1]
'dlroW olleH'
>>> a = (1,2,3,4,5,6)
>>> a[::-1]
(6, 5, 4, 3, 2, 1)
>>> a = [5,4,3,2,1]
>>> a[::-1]
[1, 2, 3, 4, 5]