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

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

快速链接到答案:

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


当前回答

对象数据模型

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

您可以重写任何运算符(* + - // / % ^ == < > <= >=。等等)。所有这些都是通过重写对象中的__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__(用于模取幂)也会在这里。

其他回答

绝密属性

>>> class A(object): pass
>>> a = A()
>>> setattr(a, "can't touch this", 123)
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', "can't touch this"]
>>> a.can't touch this # duh
  File "<stdin>", line 1
    a.can't touch this
                     ^
SyntaxError: EOL while scanning string literal
>>> getattr(a, "can't touch this")
123
>>> setattr(a, "__class__.__name__", ":O")
>>> a.__class__.__name__
'A'
>>> getattr(a, "__class__.__name__")
':O'

三元运算符

>>> 'ham' if True else 'spam'
'ham'
>>> 'ham' if False else 'spam'
'spam'

这是在2.5中添加的,在此之前你可以使用:

>>> True and 'ham' or 'spam'
'ham'
>>> False and 'ham' or 'spam'
'spam'

然而,如果你想要处理的值被认为是假的,有一个区别:

>>> [] if True else 'spam'
[]
>>> True and [] or 'spam'
'spam'

下划线,它包含解释器显示的最新输出值(在交互式会话中):

>>> (a for a in xrange(10000))
<generator object at 0x81a8fcc>
>>> b = 'blah'
>>> _
<generator object at 0x81a8fcc>

一个方便的web浏览器控制器:

>>> import webbrowser
>>> webbrowser.open_new_tab('http://www.stackoverflow.com')

内置的http服务器。提供当前目录下的文件:

python -m SimpleHTTPServer 8000

在退出

>>> import atexit

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!

嵌套函数参数重绑定

def create_printers(n):
    for i in xrange(n):
        def printer(i=i): # Doesn't work without the i=i
            print i
        yield printer