💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 4.1. 概览 下面是一个完整可运行的 Python 程序。大概看一下这段程序,你应该可以理解不少了。用数字标出的行阐述了 [第 2 章 _第一个 Python 程序_](../getting_to_know_python/index.html "第 2 章 第一个 Python 程序") 中涉及的一些概念。如果剩下来的代码看起来有点奇怪,不用担心,通过阅读本章你将会理解所有这些。 ## 例 4.1. `apihelper.py` 如果您还没有下载本书附带的样例程序, 可以 [下载本程序和其他样例程序](http://www.woodpecker.org.cn/diveintopython/download/diveintopython-exampleszh-cn-5.4b.zip "Download example scripts")。 ``` def info(object, spacing=10, collapse=1): """Print methods and doc strings. 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__ ``` | | | | --- | --- | | \[1\] | 该模块有一个声明为 `info` 的函数。根据它的[函数声明](../getting_to_know_python/declaring_functions.html "2.2. 函数声明")可知,它有三个参数: `object`、`spacing` 和 `collapse`。实际上后面两个参数都是可选参数,关于这点你很快就会看到。 | | \[2\] | `info` 函数有一个多行的 [`doc string`](../getting_to_know_python/documenting_functions.html "2.3. 文档化函数"),简要地描述了函数的功能。注意这里并没有提到返回值;单独使用这个函数只是为了这个函数产生的效果,并不是为了它的返回值。 | | \[3\] | 函数内的代码是[缩进](../getting_to_know_python/indenting_code.html "2.5. 代码缩进")形式的。 | | \[4\] | `if __name__` [技巧](../getting_to_know_python/testing_modules.html#odbchelper.ifnametrick)允许这个程序在自己独立运行时做些有用的事情,同时又不妨碍作为其它程序的模块使用。在这个例子中,程序只是简单地打印出 `info` 函数的 `doc string`。 | | \[5\] | [`if` 语句](../getting_to_know_python/testing_modules.html#odbchelper.ifnametrick)使用 `==` 进行比较,而且不需要括号。 | `info` 函数的设计意图是提供给工作在 Python IDE 中的开发人员使用,它可以接受任何含有函数或者方法的对象 (比如模块,含有函数,又比如list,含有方法) 作为参数,并打印出对象的所有函数和它们的 `doc string`。 ## 例 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 ``` 缺省地,程序输出进行了格式化处理,以使其易于阅读。多行 `doc string` 被合并到单行中,要改变这个选项需要指定 _`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. ```