如果你不熟悉某个Python模块,你可以通过如下方法获得帮助信息:
- built-in的dir函数
- built-in的help函数
- 使用pydoc模块
- 使用inspect模块
- Google搜索(本帖介绍前4种方法,不需要联网)
dir
dir()函数可以查看对像内所有属于及方法。
在Python中任何东西都是对像,数据类型,模块等,都有自己的属性和方法。除了常用方法外,其它的你不需要全部记住,交给dir()函数就好了。
如果不向dir传入任何参数:dir()
,它输出当前域内的属性和方法。如:
查看指定对象的属性和方法:
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>
也可以直接传入要查询的模块:
>>> import numpy
>>> help(numpy)
>>> help(numpy.sin)
q 退出
只要安装的模块包含文档,就可以使用help函数查看帮助信息。
pydoc
pydoc可以从Python模块中自动生成文档。
查看pydoc帮助文档:
>>> import pydoc
>>> help(pydoc)
$ pydoc numpy
启动http服务,使用浏览器查看文档:
$ pydoc -b
Server ready at http://localhost:58592/
Server commands: [b]rowser, [q]uit
server>
inspect
inspect模块可以在运行时帮助我们确定对象类型。对应的函数如下:
- ismodule()
- isclass()
- ismethod()
- isfunction()
- isgeneratorfunction()
- isgenerator()
- istraceback()
- isframe()
- iscode()
- isbuiltin()
- isroutine()
使用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