ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 4.9. 小结 `apihelper.py` 程序和它的输出现在应该非常清晰了。 ``` 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__ ``` `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 ``` 在研究下一章前,确保你可以无困难的完成下面这些事情: * 用[可选和命名参数](optional_arguments.html "4.2. 使用可选参数和命名参数")定义和调用函数 * 用 [`str`](built_in_functions.html#apihelper.str.intro "例 4.6. str 介绍") 强制转换任意值为字符串形式 * 用 [`getattr`](getattr.html "4.4. 通过 getattr 获取对象引用") 动态得到函数和其它属性的引用 * 扩展列表解析语法实现[列表过滤](filtering_lists.html "4.5. 过滤列表") * 识别 [`and-or` 技巧](and_or.html "4.6. and 和 or 的特殊性质")并安全地使用它 * 定义 [`lambda` 函数](lambda_functions.html "4.7. 使用 lambda 函数") * 将函数赋值给变量然后通过引用变量调用函数。我强调的已经够多了:这种思考方式对于提高对 Python 的理解力至关重要。在本书中你会随处可见这种技术的更复杂的应用。