Python檢視模組幫助/文件

周小董發表於2019-01-30

如果你不熟悉某個Python模組,你可以通過如下方法獲得幫助資訊:

  • built-in的dir函式
  • built-in的help函式
  • 使用pydoc模組
  • 使用inspect模組
  • Google搜尋(本帖介紹前4種方法,不需要聯網)

dir

dir()函式可以檢視對像內所有屬於及方法。

在Python中任何東西都是對像,資料型別,模組等,都有自己的屬性和方法。除了常用方法外,其它的你不需要全部記住,交給dir()函式就好了。

如果不向dir傳入任何引數:dir(),它輸出當前域內的屬性和方法。如:

Python檢視模組幫助/文件

檢視指定物件的屬性和方法:

Python檢視模組幫助/文件

Python檢視模組幫助/文件

help

Python內建的幫助功能,它實際上是基於pydoc.help

如果help不帶任何引數,會進入互動模式:

>>> help()
 
Welcome to Python 3.5's help utility!
 
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.
 
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".
 
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
 
help>

image.png

也可以直接傳入要查詢的模組:

>>>  import numpy
>>>  help(numpy)
>>>  help(numpy.sin)

Python檢視模組幫助/文件

q 退出

只要安裝的模組包含文件,就可以使用help函式檢視幫助資訊。

pydoc

pydoc可以從Python模組中自動生成文件。

檢視pydoc幫助文件:

>>>  import pydoc
>>>  help(pydoc)

Python檢視模組幫助/文件

$  pydoc numpy

啟動http服務,使用瀏覽器檢視文件:

$  pydoc  -b
Server ready at  http://localhost:58592/
Server commands:  [b]rowser,  [q]uit
server>

Python檢視模組幫助/文件

inspect

inspect模組可以在執行時幫助我們確定物件型別。對應的函式如下:

  • ismodule()
  • isclass()
  • ismethod()
  • isfunction()
  • isgeneratorfunction()
  • isgenerator()
  • istraceback()
  • isframe()
  • iscode()
  • isbuiltin()
  • isroutine()

Python檢視模組幫助/文件
使用getmembers()獲得物件所有成員:

>>>  len(inspect.getmembers(tensorflow))
471
>>>  len(inspect.getmembers(tensorflow,  inspect.isclass))
50

使用getdoc獲得文件物件:

>>>  inspect.getdoc(dict)

"dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n    (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n    d = {}\n    for k, v in iterable:\n        d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n    in the keyword argument list.  For example:  dict(one=1, two=2)"

檢視inspect幫助:

>>>  help(inspect)

來源:http://blog.topspeedsnail.com/archives/10206#more-10206

相關文章