2015-02-24 31 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