[英]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. Class_Interface_file返回一个类名列表示例['Social','Audio']我在方法get_class_members中有问题。 I want to print the comments for each member function I discover through inspect.getmembers.
我想通过inspect.getmembers打印我发现的每个成员函数的注释。 I dono how to concat className with value of each_item.
我不知道如何使用each_item的值来连接className。
or is it possible to directly print documentation of member functions which comes from each_item ? 或者是否可以直接打印来自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. 我在模块三角形中有一个类Triangle,有一些方法。
>>>import inspect
>>>import triangle
>>>mems = inspect.getmembers(triangle.Triangle)
>>>mems
[('__doc__', None), ('__init__','<unboound method.....>), etc)]
getmembers()
returns a list of tuples. getmembers()
返回元组列表。 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. 所以在你的代码循环中,你要求
each_item[0].__doc__
,[0]引用包含函数名称的字符串。 So that line returns just the __doc__
of string objects. 因此该行只返回字符串对象的
__doc__
。 Changing this to [1] will return the __doc__
for the actual method: 将其更改为[1]将返回实际方法的
__doc__
:
>>>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. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.