当前位置 博文首页 > zy010101博客:Python——查看帮助手册

    zy010101博客:Python——查看帮助手册

    作者:[db:作者] 时间:2021-06-11 18:07

    在Python中获取帮助

    1. dir()函数

    dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
    例如,我们在python交互式环境中查看re模块的方法和属性。

    >>> import re
    >>> dir(re)
    ['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'Match', 'Pattern', 'RegexFlag', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_cache', '_compile', '_compile_repl', '_expand', '_locale', '_pickle', '_special_chars_map', '_subx', 'compile', 'copyreg', 'enum', 'error', 'escape', 'findall', 'finditer', 'fullmatch', 'functools', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'template']
    

    当然,也可以获取内置类型的方法和属性,下面展示了如何获取字符串类型的属性和方法。

    >>> s = ''
    >>> dir(s)
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
    

    dir()方法只能获取模块的属性和方法,在现在编辑器如此人性化的时代下可能很少会用到了。

    2. help()函数

    dir()函数只是简要的给出了属性和方法的名字,甚至你无法区分哪些是属性,哪些是方法。不过python提供了help()函数,可以查找出它们的功能是什么。例如在交互式终端输入下面的代码:
    help(s.split)
    输出如下:

    Help on built-in function split:
    
    split(sep=None, maxsplit=-1) method of builtins.str instance
    Return a list of the words in the string, using sep as the delimiter string.
    
    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.
    

    当然了,你也可以使用help()函数直接查询一个模块的帮助手册。例如,查询正则模块的帮助手册。
    help(re)

    3. pydoc工具

    pydoc是一个更加强大的使用帮助手册的方法。在Linux系统下,你在终端输入如下命令即可打开pydoc生成的HTML文档。
    pydoc3 -b
    这个命令前面的pydoc3可能会随着你的python版本而变化。输入该命令之后,会在你的默认浏览器中打开一个帮助页面,如下所示:
    在这里插入图片描述
    如果没有自动启动浏览器,那么使用终端上显示的地址来访问即可。

    在这里插入图片描述