Python编程语言中有哪些鲜为人知但很有用的特性?
尽量将答案限制在Python核心。
每个回答一个特征。
给出一个例子和功能的简短描述,而不仅仅是文档链接。
使用标题作为第一行标记该特性。
快速链接到答案:
参数解包
牙套
链接比较运算符
修饰符
可变默认参数的陷阱/危险
描述符
字典默认的.get值
所以测试
省略切片语法
枚举
其他/
函数作为iter()参数
生成器表达式
导入该
就地值交换
步进列表
__missing__物品
多行正则表达式
命名字符串格式化
嵌套的列表/生成器推导
运行时的新类型
.pth文件
ROT13编码
正则表达式调试
发送到发电机
交互式解释器中的制表符补全
三元表达式
试着/ / else除外
拆包+打印()函数
与声明
Doctest:同时进行文档和单元测试。
从Python文档中提取的示例:
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
您可以用元类重写类的mro
>>> class A(object):
... def a_method(self):
... print("A")
...
>>> class B(object):
... def b_method(self):
... print("B")
...
>>> class MROMagicMeta(type):
... def mro(cls):
... return (cls, B, object)
...
>>> class C(A, metaclass=MROMagicMeta):
... def c_method(self):
... print("C")
...
>>> cls = C()
>>> cls.c_method()
C
>>> cls.a_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'a_method'
>>> cls.b_method()
B
>>> type(cls).__bases__
(<class '__main__.A'>,)
>>> type(cls).__mro__
(<class '__main__.C'>, <class '__main__.B'>, <class 'object'>)
藏起来可能是有原因的。:)
重新加载模块可以实现“实时编码”风格。但是类实例不更新。以下是原因,以及如何解决这个问题。记住,所有东西,是的,所有东西都是一个对象。
>>> from a_package import a_module
>>> cls = a_module.SomeClass
>>> obj = cls()
>>> obj.method()
(old method output)
现在更改a_module.py中的方法,并希望更新对象。
>>> reload(a_module)
>>> a_module.SomeClass is cls
False # Because it just got freshly created by reload.
>>> obj.method()
(old method output)
这里有一种更新方法(但考虑使用剪刀运行):
>>> obj.__class__ is cls
True # it's the old class object
>>> obj.__class__ = a_module.SomeClass # pick up the new class
>>> obj.method()
(new method output)
这是“剪刀式运行”,因为对象的内部状态可能与新类所期望的不同。这适用于非常简单的情况,但除此之外,pickle是您的朋友。尽管如此,理解为什么这是有效的仍然是有帮助的。
每次打印一屏多行字符串
没有真正有用的功能隐藏在网站。_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:
动态添加的属性
如果您想通过调用来向类添加一些属性,这可能会很有用。这可以通过重写__getattribute__成员函数来实现,该成员函数在使用点操作数时被调用。让我们看一个虚拟类为例:
class Dummy(object):
def __getattribute__(self, name):
f = lambda: 'Hello with %s'%name
return f
当你实例化一个Dummy对象并进行方法调用时,你会得到以下结果:
>>> d = Dummy()
>>> d.b()
'Hello with b'
最后,您甚至可以为您的类设置属性,以便动态定义它。如果你使用Python web框架,想通过解析属性名来进行查询,这可能很有用。
我在github上有一个要点,这个简单的代码和一个朋友在Ruby上做的等效代码。
保重!