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

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

快速链接到答案:

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


当前回答

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

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

其他回答

下面是我在调试类型错误时使用的一个有用的函数

def typePrint(object):
    print(str(object) + " - (" + str(type(object)) + ")")

例如,它只是打印输入后跟类型

>>> a = 101
>>> typePrint(a)
    101 - (<type 'int'>)

内存管理

Python动态分配内存并使用垃圾收集来回收未使用的空间。一旦一个对象超出作用域,并且没有其他变量引用它,它将被恢复。我不必担心缓冲区溢出和缓慢增长的服务器进程。内存管理也是其他动态语言的一个特性,但Python在这方面做得非常好。

当然,我们必须注意循环引用,并保持对不再需要的对象的引用,但弱引用在这里有很大帮助。

列表理解

列表理解

比较更传统的(不含列表理解):

foo = []
for x in xrange(10):
  if x % 2 == 0:
     foo.append(x)

to:

foo = [x for x in xrange(10) if x % 2 == 0]

以完全动态的方式创建新类型

>>> NewType = type("NewType", (object,), {"x": "hello"})
>>> n = NewType()
>>> n.x
"hello"

哪个是完全一样的

>>> class NewType(object):
>>>     x = "hello"
>>> n = NewType()
>>> n.x
"hello"

可能不是最有用的东西,但很高兴知道。

编辑:新类型的固定名称,应该是NewType,是与类语句完全相同的东西。

编辑:调整标题,以更准确地描述功能。

懒得初始化字典中的每个字段?没有问题:

在Python > 2.3中:

from collections import defaultdict

Python中<= 2.3:

def defaultdict(type_):
    class Dict(dict):
        def __getitem__(self, key):
            return self.setdefault(key, type_())
    return Dict()

在任何版本中:

d = defaultdict(list)
for stuff in lots_of_stuff:
     d[stuff.name].append(stuff)

更新:

谢谢肯·阿诺德。我重新实现了一个更复杂的defaultdict版本。它的行为应该与标准库中的完全相同。

def defaultdict(default_factory, *args, **kw):                              

    class defaultdict(dict):

        def __missing__(self, key):
            if default_factory is None:
                raise KeyError(key)
            return self.setdefault(key, default_factory())

        def __getitem__(self, key):
            try:
                return dict.__getitem__(self, key)
            except KeyError:
                return self.__missing__(key)

    return defaultdict(*args, **kw)