4.9. 总结

现在,您应该完全理解 apihelper.py 程序及其输出。


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__

以下是 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

在进入下一章之前,请确保您能够轻松完成所有这些操作

  • 使用可选参数和命名参数定义和调用函数
  • 使用 str 将任何任意值强制转换为字符串表示形式
  • 使用 getattr 动态获取对函数和其他属性的引用
  • 扩展列表推导语法以进行列表过滤
  • 识别and-or 技巧并安全地使用它
  • 定义lambda 函数
  • 将函数赋值给变量并通过引用变量来调用函数。我无法过分强调这一点,因为这种思维方式对于提高您对 Python 的理解至关重要。在本书中,您将看到此概念的更复杂应用。