##language:zh ''' Python哲学-内省 ''' -- ZoomQuiet [<<DateTime(2004-12-22T10:31:46Z)>>] <<TableOfContents>> = 内省的威力 = * AlbertLee * [[http://python.cn/pipermail/python-chinese/2004-August/004091.html|Xie Yanbo]] 引发 * {{http://www.python.org/pics/batteries-included.jpg}} * '''Remember, Python comes with batteries included!''' * PyBatteriesIncluded -- 使用内省的功能,获得丰富的信息 * Python 可以使用内省的功能,获得丰富的信息。 == 类什么方法? == 例如,如果我们想知道 dict 具有什么方法,那么我们可以像下面这样: {{{ >>> dir({}) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] >>> }}} 好,现在我们得到了一个列表,那么这些都是干什么用的呢? 我们需要更多的信息: {{{ >>> type({}.update) <type 'builtin_function_or_method'> }}} 上面,我们使用 type() 得知 dict 的 update 方法是一个 'builtin_function_or_method' ,这说明这是一个Python原生代码(在Python源代码中用C写成)。update究竟怎么用呢? 原来 python 已经给我们嵌入了文档: {{{ >>> {}.update.__doc__ 'D.update(E) -> None. Update D from E: for k in E.keys(): D[k] = E[k]' }}} 此处的 __doc__ 是一个函数中的一个文档字符串,另外还有 module,class 的 __doc__。 在自己写程序时,可以使用类似下面的方法增加__doc__: {{{ >>> def add(a,b): """ My demo add method.""" return a + b >>> add.__doc__ ' My demo add method.' }}} == 自动获得模块信息的探讨 == :(初步探索) 例子程序: {{{ # AMod.py # module AMod """ A demo module for auto get __doc__ This is a module __doc__ """ def Afun(): """ Afun 's __doc__ """ class AClass: """ AClass __doc__ """ def __init__(self): pass def classFun(): """ Class method's __doc__ """ pass }}} === 获得模块信息: === {{{ # GetInfo.py import AMod import inspect info = """ Module info: """ info = info + "Module Name:" + AMod.__name__ + '\n' \ + "Module file:" + AMod.__file__ + '\n' \ + "Module doc:" + AMod.__doc__ + '\n\n' mod_dict = AMod.__dict__ for obj in mod_dict.keys(): info = info + "%s \n\t%s\n"%(obj, type(mod_dict[obj])) if inspect.isroutine(mod_dict[obj]): info = info + "\tfunction doc: %s\n"%(mod_dict[obj].__doc__) if inspect.isclass(mod_dict[obj]): info = info + "\tClass doc: %s\n"%(mod_dict[obj].__doc__) print info }}}