您当前位置:首页 > 深入 Python > 自省的强大功能 | << >> | ||||
深入 Python从 Python 新手到专业人士 |
本章介绍 Python 的优势之一:自省。如您所知,Python 中的一切都是对象,而自省是指代码将内存中的其他模块和函数视为对象,获取有关它们的信息并对其进行操作。在此过程中,您将定义没有名称的函数,使用无序的参数调用函数,以及引用您事先不知道名称的函数。
这是一个完整的、可运行的 Python 程序。只需查看代码,您就应该能理解很多内容。带编号的行说明了第二章“您的第一个 Python 程序”中介绍的概念。如果其余代码看起来很吓人,请不要担心;您将在本章中学习所有相关内容。
如果您尚未下载,则可以下载本书中使用的此示例和其他示例。
def info(object, spacing=10, collapse=1):![]()
![]()
"""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__":
![]()
print info.__doc__
info 函数旨在供您(程序员)在 Python IDE 中工作时使用。它接受任何具有函数或方法的对象(例如具有函数的模块或具有方法的列表),并打印出函数及其 文档字符串。
>>> 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 参数指定更大的值,以使输出更易于阅读。
>>> 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.
<< 总结 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
使用可选参数和命名参数 >> |