diveintopython.org
Python for experienced programmers

2.10. 小结

apihelper.py 程序和它的输出现在应该非常清楚了。

例 2.30. apihelper.py

from types import BuiltinFunctionType, BuiltinMethodType, \
    FunctionType, MethodType, ClassType

def help(object, spacing=10, collapse=1):
    """Print methods and doc strings.
    
    Takes module, class, list, dictionary, or string."""
    typeList = (BuiltinFunctionType, BuiltinMethodType, FunctionType, MethodType, ClassType)
    methodList = [method for method in dir(object) if type(getattr(object, method)) in typeList]
    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 help.__doc__

例 2.31. apihelper.py 的输出

>>> from apihelper import help
>>> li = []
>>> help(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

在研究下一章之前,确保你可以无困难地完成下面的事情: