[511]python查看模块帮助/文档

本文介绍了在Python中查询模块信息的四种方法:使用dir()函数查看对象的所有属性和方法;使用help()函数获取内置帮助;利用pydoc模块自动生成文档;以及使用inspect模块进行运行时类型检查。这些方法有助于深入理解Python模块的功能。

文章目录


如果你不熟悉某个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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值