2015-02-24 32 views
3

最近我发现了内置的help(),它为模块,函数,方法,类等等打印了一些信息。但是它究竟在哪里找到它显示的信息呢?​​对此没有提供任何提示。help()在Python中找到信息?

>>> import base64 
>>> help(base64) 
Help on module base64: 

NAME 
    base64 - RFC 3548: Base16, Base32, Base64 Data Encodings 

FILE 
    /usr/lib/python2.7/base64.py 
.. 
+0

HTTP的帮助://计算器。com/questions/5430020/python-how-to-get-information-about-a-function http://stackoverflow.com/questions/139180/listing-all-functions-in-a-python-module – 2015-02-24 14:41:58

回答

5

如果你简单地做,help(help),你会得到

Help on _Helper in module site object: 

class _Helper(__builtin__.object) 
| Define the builtin 'help'. 
| This is a wrapper around pydoc.help (with a twist). 
| 
| Methods defined here: 
| 
| __call__(self, *args, **kwds) 
| 
| __repr__(self) 
| 
| ---------------------------------------------------------------------- 
| Data descriptors defined here: 
| 
| __dict__ 
|  dictionary for instance variables (if defined) 
| 
| __weakref__ 
|  list of weak references to the object (if defined) 

基本上,helppydoc.help获取输入。报价,pydoc documentation

对于模块,类,函数和方法,所显示的文档被从对象的文档字符串(即__doc__属性)衍生的,并递归其佐证的构件。如果没有文档字符串,pydoc会尝试从源文件中的类,函数或方法的定义之上或模块(请参阅inspect.getcomments())的顶部的注释行块获取说明。

内置函数help()调用交互式解释器中的联机帮助系统,它使用pydoc在控制台上以文本形式生成其文档。


但到底它在哪里找到它显示的信息?

上面引用的粗体文本回答了这个问题。

1

正是在site.py,如果使用help.__class__你会看到它是site._Helper这仅仅是一个围绕pydoc.help包装:

class _Helper(object): 
    """Define the builtin 'help'. 
    This is a wrapper around pydoc.help (with a twist). 

    """ 

    def __repr__(self): 
     return "Type help() for interactive help, " \ 
       "or help(object) for help about object." 
    def __call__(self, *args, **kwds): 
     import pydoc 
     return pydoc.help(*args, **kwds) 

def sethelper(): 
    __builtin__.help = _Helper() 

help(object)是:从site.py

In [1]: help.__class__ 
Out[1]: site._Helper 

_Helper类相当于__builtin__.help(object),它将对象传递给pydoc.help

1

如果您创建以下结构

C(目录) - > __init__.py(此目录中的文件)

然后写以下为__init__.py

'''Some help''' 

并运行help(C)。你会显示以下

Help on package C: 

NAME 
    C - Some help 

FILE 
    /C/__init__.py 

PACKAGE CONTENTS 

在这种情况下help()会从文档字符串(中的一三'之间)

+0

你可以使用'\\'来转义__斜体文本问题 - > \ _ \ _ init__.py – Holloway 2015-02-24 14:54:08

+0

@Trengot,谢谢,现在看起来好多了。 – ForceBru 2015-02-24 14:55:48

+0

我经常发现自己用反引号写了'__init __。py',这也解决了这个问题。 – 2015-02-24 14:58:43