第四章. 自省的强大功能

本章介绍 Python 的优势之一:自省。如您所知,Python 中的一切都是对象,而自省是指代码将内存中的其他模块和函数视为对象,获取有关它们的信息并对其进行操作。在此过程中,您将定义没有名称的函数,使用无序的参数调用函数,以及引用您事先不知道名称的函数。

4.1. 深入探讨

这是一个完整的、可运行的 Python 程序。只需查看代码,您就应该能理解很多内容。带编号的行说明了第二章“您的第一个 Python 程序”中介绍的概念。如果其余代码看起来很吓人,请不要担心;您将在本章中学习所有相关内容。

示例 4.1. apihelper.py

如果您尚未下载,则可以下载本书中使用的此示例和其他示例


def info(object, spacing=10, collapse=1): 1 2 3
    """Print methods and docstrings.
    
    Takes module, class, list, dictionary, or string."""
    methodList = [method for method in dir(object) if callable(getattr(object, method))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                      (method.ljust(spacing),
                       processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])

if __name__ == "__main__":                4 5
    print info.__doc__
1 此模块有一个函数 info。根据其函数声明,它接受三个参数:objectspacingcollapse。您很快就会看到,最后两个实际上是可选参数。
2 info 函数有一个多行的文档字符串,它简洁地描述了函数的用途。请注意,没有提到返回值;此函数将仅用于其效果,而不是其值。
3 函数内的代码是缩进的
4 if __name__ 技巧允许此程序在单独运行时执行一些有用的操作,而不会干扰它作为其他程序的模块的使用。在这种情况下,程序只是简单地打印出 info 函数的 文档字符串
5 if 语句使用 == 进行比较,并且不需要括号。

info 函数旨在供您(程序员)在 Python IDE 中工作时使用。它接受任何具有函数或方法的对象(例如具有函数的模块或具有方法的列表),并打印出函数及其 文档字符串

示例 4.2. apihelper.py 的使用示例

>>> from apihelper import info
>>> li = []
>>> info(li)
append     L.append(object) -- append object to end
count      L.count(value) -> integer -- return number of occurrences of value
extend     L.extend(list) -- extend list by appending list elements
index      L.index(value) -> integer -- return index of first occurrence of value
insert     L.insert(index, object) -- insert object before index
pop        L.pop([index]) -> item -- remove and return item at index (default last)
remove     L.remove(value) -- remove first occurrence of value
reverse    L.reverse() -- reverse *IN PLACE*
sort       L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1

默认情况下,输出格式易于阅读。多行 文档字符串 会折叠成一行,但可以通过为 collapse 参数指定 0 来更改此选项。如果函数名称超过 10 个字符,则可以为 spacing 参数指定更大的值,以使输出更易于阅读。

示例 4.3. apihelper.py 的高级用法

>>> import odbchelper
>>> info(odbchelper)
buildConnectionString Build a connection string from a dictionary Returns string.
>>> info(odbchelper, 30)
buildConnectionString          Build a connection string from a dictionary Returns string.
>>> info(odbchelper, 30, 0)
buildConnectionString          Build a connection string from a dictionary
    
    Returns string.