一切都基于下面这个函数定义(apihelper.py)
def info(object, spacing = 10, callapse=1):
"""print methods and doc srings.
takes module, class, list, dictionary, or string. """
methodlist = [method for method in dir(object) if callable(getattr(object, method))]
processFunc = callapse 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__
解释了几个基本的内置函数:
第一个dir,用于列举一个对象的所有属性、函数、方法、doc string等内容。
第二个是getattr,这个类似于.net/java里面的反射。通过getattr可以获取某个对象的方法引用,然后直接调用他。例如getattr(apihelper, “info")(obj). apihelper是一个模块。
第三个是callable,用于判断获得属性是不是一个可调用的对象,也就是函数、方法。
第四个是lambda。这个就是定义一个inline的函数。例如lambda s:print "this is a good str %s" % s.
第五个是列表过滤。methodlist = [method for method in dir(object) if callable(getattr(object, method))]。这个很容易理解
第六个是and 和 or。这个稍微多一点。在python里面,and和or都是从左向右进行计算。and遇到第一个假值就返回,如果都是真,返回最后一个真。or遇到第一个真值返回,如果都是假,返回最后一个假。另外,and与or有一个特殊的用法,就是实现C里面bool?(if true do):(if false do).就是这样:condition and fun_if_true or fun_if_false