python离线获取帮助

在学习和使用python时,我们可以通过查看在线的python文档来获取需要的信息。但是在离线情况下我们如何获取我们需要的信息呢?其实很容易,我们都知道python是一种自文档化语言,大多数函数和模块都包含简短的解释,你无需求助于图书和网站就可以搞明白如何使用它们。

四大帮助函数

下面是四种基本的python内置函数,它们可以帮助我们获取python内置函数和模块的用法和信息。

  • dir() function
  • help() function
  • type() function
  • __doc__ function
函数说明
dir()列出模块中的函数
help()打印对象的相关信息
type()返回对象的类型
__doc__返回对象或模块的文档字符串

Note:本文以python3为例,python2用法基本相同。

dir([object])

不给参数时, dir() 就罗列出当前已定义的所有名字。如果使用参数,就会返回该对象所有有效的函数、变量等。下面是几个简单的例子:

>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> import struct
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'struct']
>>> dir(struct)   # show the names in the struct module
['Struct', '__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']

在上面的例子中,导入struct模块后,如果不加任何参数的话,dir()返回的是当前域内已定义的所有名字,即['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'struct']。使用struct参数后,dir()列举出struct类的属性。

>>> class Shape(object):
        def __dir__(self):
            return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'perimeter', 'location']

如果一个对象中有一个名为__dir__()的方法,那么dir([object])必须返回__dir__()列出的属性列表。

>>> x=32
>>> dir(x)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
...
>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
...

dir()的参数还可以是具体的变量,返回变量类型相关属性。

help([object])

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> int
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)
 |      Return self+value.
>>> help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.

使用str作为参数就会显示有关str类的相关帮助文档。

type(object)

顾名思义,type()函数返回对象的类型。

>>> x = 55
>>> type(x)
<type 'int'>

>>> y = "Hello World!"
>>> type(y)
<type 'str'>

>>> name_list = ["John", "Jerry", "Jimmy", "Jackie"]
>>> type(name_list)
<type 'list'>

>>> name_tuple = ("John", "55", "Jerry", "5", "Jimmy", "545")
>>> type(name_tuple)
<type 'tuple'>

>>> name_dict = {"John": 55, "Jerry": 545, "Jimmy": 999}
>>> type(name_dict)
<type 'dict'>

>>> type(__builtins__)
<type 'module'>

>>> def My_String():
...  print "Hello World!"
...
>>> type(My_String)
<type 'function'>

__doc__

另一个实用的技巧是打印函数或者模块等的文档字符串。

>>> import math
>>> print(math.sin.__doc__)
sin(x)

Return the sine of x (measured in radians).

大多数python内置函数都有简短的文档字符串,这些字符串通常位于模块或者函数的开始部分。

>>> print(bin.__doc__)
Return the binary representation of an integer.

   >>> bin(2796202)
   '0b1010101010101010101010'

对比

下面通过一个简单的例子对比四个函数。

>>> import os
>>> dir(os)
['F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', ...
>>> help(os)
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

DESCRIPTION
    This exports:
      - all functions from posix, nt or ce, e.g. unlink, stat, etc.
      - os.path is either posixpath or ntpath
      - os.name is either 'posix', 'nt' or 'ce'.
      - os.curdir is a string representing the current directory ('.' or ':')
      - os.pardir is a string representing the parent directory ('..' or '::')
      - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
      - os.extsep is the extension separator (always '.')
      - os.altsep is the alternate pathname separator (None or '/')
      ...
      |  Method resolution order:
      |      OSError
      |      Exception
      |      BaseException
      |      object
      |  
      |  Methods defined here:
      |  
      |  __init__(self, /, *args, **kwargs)
      |      Initialize self.  See help(type(self)) for accurate signature.
      |  
      |  __new__(*args, **kwargs) from builtins.type
      |      Create and return a new object.  See help(type) for accurate signature.
      ...      
>>> type(os)
<class 'module'>
>>> print(os.__doc__)
OS routines for NT or Posix depending on what system we're on.

This exports:
  - all functions from posix, nt or ce, e.g. unlink, stat, etc.
  - os.path is either posixpath or ntpath
  - os.name is either 'posix', 'nt' or 'ce'.
  - os.curdir is a string representing the current directory ('.' or ':')
  - os.pardir is a string representing the parent directory ('..' or '::')
  - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  - os.extsep is the extension separator (always '.')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).

参考资料

  1. The linux juggernaut, http://www.linuxnix.com/python-builtin-helpdir-help-type-and-___doc_-functions/#%22Here%20is%20my%20list%20of%20online%20resources%22

  2. Python 3.5.2 documentation, https://docs.python.org/3/

  3. Python编程入门, [加]Toby Donaldson著, 人民邮电出版社

知识共享许可协议
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值