Skip to main content
 首页 » 编程设计

python之如何将函数的文档字符串放入变量中

2025年05月04日24mfrbuaa

这些命令都不会检索函数的文档字符串并将其分配给变量。如何实现?

我尝试了各种各样的事情。其中之一是 help 函数,但它似乎激活了整个程序,而不是返回一个字符串。我尝试了各种命令,但没有一个能检索文档字符串。

import PIL 
 
PILCommands=dir('PIL') 
 
ListA=[] 
ListB=[] 
ListC=[] 
ListD=[] 
ListE=[] 
LisfF=[] 
ListG=[] 
ListH=[] 
 
for x in PILCommands: 
    print(x) 
    try: 
        ListA.append(x.__doc__) 
    except: 
        pass 
    try: 
        ListB.append(x.__doc__()) 
    except: 
       pass 
    try: 
        ListC.append(str(x)) 
    except: 
        pass 
   try: 
       ListD.append(help(x)) 
   except: 
       pass 
   try: 
       ListE.append(eval("x.__doc__")) 
   except: 
       pass 
   try: 
       ListF.append(eval("inspect.getdoc(x)")) 
   except: 
        pass 
   try: 
        ListG.append(eval("dir(x)")) 
   except: 
        pass 
   try: 
        ListH.append(eval("PIL.x.__doc__")) 
   except: 
        pass 
 
print 
print("Command1: x.__doc__") 
print(ListA) 
print 
print("Command1: x.__doc__()") 
print(ListB) 
print 
print("Command1: str(x)") 
print(ListC) 
print 
print("help(x)") 
print(ListD) 
print 
print('Command1: eval("eval("x.__doc__")') 
print(ListE) 
print 
print('Command1: eval("inspect.getdoc(x)")') 
print(ListE) 
print 
print('Command1: eval("dir(x)")') 
print(ListG) 
print 
print('Command1: eval("PIL.x.__doc__")') 
print(ListG) 

回答:

python << EOF 
import inspect 
import PIL  
doc = inspect.getdoc(PIL) 
print doc 
print type(doc) 
EOF 

所以它没有文档。

请您参考如下方法:

您可以使用 inspect.getdoc ,这将处理对象的文档字符串并将其作为字符串返回:

>>> import inspect 
>>> doc = inspect.getdoc(I) 
 
>>> print(doc) 
This is the documentation string (docstring) of this function . 
It contains an explanation and instruction for use .  

通常文档存储在 __doc__ 中属性:

>>> doc = I.__doc__ 
>>> print(doc) 
 
    This is the documentation string (docstring) of this function . 
    It contains an explanation and instruction for use .  

但是 __doc__ 不会被清理:它可能包含前导和尾随的空换行符,并且缩进可能不一致。所以 inspect.getdoc 应该是首选。

以下内容基于您的原始问题:

要获取 PIL 函数的文档,您可以使用:

>>> import PIL 
>>> import inspect 
 
>>> doc = inspect.getdoc(PIL.Image.fromarray) 
>>> print(doc) 
Creates an image memory from an object exporting the array interface 
(using the buffer protocol). 
 
If obj is not contiguous, then the tobytes method is called 
and :py:func:`~PIL.Image.frombuffer` is used. 
 
:param obj: Object with array interface 
:param mode: Mode to use (will be determined from type if None) 
  See: :ref:`concept-modes`. 
:returns: An image object. 
 
.. versionadded:: 1.1.6 

要获取模块中所有函数的文档,您需要使用 getattr:

for name in dir(PIL.Image): 
    docstring = inspect.getdoc(getattr(PIL.Image, name))  # like this 

获取所有文档字符串的列表:

list_of_docs = [inspect.getdoc(getattr(PIL, obj)) for obj in dir(PIL)] 

或者如果你需要相应的名字那么字典会更好:

list_of_docs = {obj: inspect.getdoc(getattr(PIL, obj)) for obj in dir(PIL)} 

然而,并不是所有的东西实际上都有文档。例如 PIL.Image 模块没有文档字符串:

>>> PIL.Image.__doc__ 
None 
>>> inspect.getdoc(PIL.Image) 
None 

当尝试获取实例的文档字符串时,您可能会得到令人惊讶的结果:

>>> inspect.getdoc(PIL.__version__) 
str(object='') -> str 
str(bytes_or_buffer[, encoding[, errors]]) -> str 
 
Create a new string object from the given object. If encoding or 
errors is specified, then the object must expose a data buffer 
that will be decoded using the given encoding and error handler. 
Otherwise, returns the result of object.__str__() (if defined) 
or repr(object). 
encoding defaults to sys.getdefaultencoding(). 
errors defaults to 'strict'. 

那是因为 PIL.__version__ 是一个字符串实例,只显示其类的文档字符串:str:

>>> inspect.getdoc(str)  # the built-in "str" 
str(object='') -> str 
str(bytes_or_buffer[, encoding[, errors]]) -> str 
 
Create a new string object from the given object. If encoding or 
errors is specified, then the object must expose a data buffer 
that will be decoded using the given encoding and error handler. 
Otherwise, returns the result of object.__str__() (if defined) 
or repr(object). 
encoding defaults to sys.getdefaultencoding(). 
errors defaults to 'strict'.