简体   繁体   中英

How print python method documentation using inspect or __doc__ method

I have following code :

import os
import imp
import sys
import inspect
import urlparse
from cgi import escape

def get_module(ClassName, Path):
    fp, pathname, description = imp.find_module(ClassName, [Path])
    module_loaded = imp.load_module(ClassName, fp, pathname, description)
    return module_loaded


def get_class_members(className):
    print "Members of  "+str(className)
    member_functions = inspect.getmembers(className,    predicate=inspect.ismethod)
    for each_item in member_functions:
        print each_item[0].__doc__

def get_all_classes(path, module):

    module_loaded = None
    sys.path.append(path)

    module_loaded = get_module(module, path)

    if None != module_loaded:
        class_list = module_loaded.get_all_classes()
        print "classes are "+str(class_list)
        return class_list




def main():
    class_list = get_all_classes('.', 'Class_Interface_File')
    for each_class in class_list:
        temp_module = get_module(each_class, '.')
        my_class = getattr(temp_module, each_class)
        instance = my_class()
        get_class_members(instance)
        print "-----------"

if __name__ == "__main__":
    main()

Class_Interface_file returns a list of classnames example ['Social', 'Audio'] I have issue here in method get_class_members. I want to print the comments for each member function I discover through inspect.getmembers. I dono how to concat className with value of each_item.

or is it possible to directly print documentation of member functions which comes from each_item ?

please help on this.

Okay, did some playing around with your code....

I have a class Triangle in a module triangle with some methods.

>>>import inspect
>>>import triangle
>>>mems = inspect.getmembers(triangle.Triangle)
>>>mems
[('__doc__', None), ('__init__','<unboound method.....>), etc)]

getmembers() returns a list of tuples. So in your code, looping through this, you're asking for each_item[0].__doc__ , [0] refers to the string containing the name of the function. So that line returns just the __doc__ of string objects. Changing this to [1] will return the __doc__ for the actual method:

>>>mems[3][0]  #the name of the function itself
'drawEquilateral'
>>>#here I reference the second tuple element of the fourth member
...
>>>mems[3][1].__doc__
'draw an equilateral triangle'
>>>"Method %s:  %s" %(mems[3][0], mems[3][1].__doc__)
'Method drawEquilateral: draw an equilateral triangle'

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM