【Python学习手册(第四版)】学习笔记15-文档(注释、PyDoc等)

个人总结难免疏漏,请多包涵。更多内容请查看原文。本文以及学习笔记系列仅用于个人学习、研究交流。

本文主要介绍程序的文档概念。包括为程序编写的注释,以及内置工具的文档。讲解文档字符串、Python的在线手册等资源、以及PyDoc的help函数和网页接口。

本文较简单,5-10分钟即可。


目录

Python文档资源

#注释

dir函数

文档字符串:__doc__

用户定义的文档字符串

文档字符串标准

内置文档字符串

PyDoc:help函数

PyDoc:HTML报表

标准手册集

网络资源

已出版的书籍


这里说的文档是用于编写Python代码的文档(注释或其他文字)的技术和工具。尽管Python代码具有可读性,但在合适的地方放一些可读的注释,能很大程度上帮助其他人了解你的程序所做的工作。Python包含了可以使文档的编写变得更简单的语法和工具。

主要介绍两方面,一是涉及了Python的语法模型,二是Python工具集的读者资源。

Python文档资源

Python预置的功能数量很多:内置函数和异常、预先定义的对象属性和方法、标准库模块等。通常困扰初学者的头几个问题之一是怎么找到这些内置工具的信息。

这里提供了一些Python可用的文档资源。还会介绍文档字符串(docstring)以及使用它们的PyDoc系统。这些话题对核心语言本身算是外围的话题。但是,一旦编写代码的能力上来了这就变成是重要的知识了。

可以从很多地方查找Python信息,而且一般都是信息量逐渐增加。

#注释

井字号注释是代码编写文档的最基本方式。

Python会忽略#之后所有文字(只要#不是位于字符串常量中),所以可以在这个字符之后插入一些对程序员有意义的文字和说明。不过,这类注释只能从源代码文件中看到

要编写能够更广泛的使用的注释,请使用文档字符串

当前最佳的实践经验通常都表明,文档字符串最适于较大型功能的文档(例如,“我的文件做这些事”),而#注释最适用于较小功能的文档(例如,“这个奇怪的表达式做这些事”)。

dir函数

内置的dir函数是抓取对象内可用所有属性列表的简单方式(例如,对象的方法以及较简单的数据项)。它能够调用任何有属性的对象。

例如,要找出标准库中的sys模块有什么可以用,可将其导入,并传给dir:

import sys
dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', '_base_executable', '_clear_type_cache', '_current_exceptions', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_getframemodulename', '_git', '_home', '_setprofileallthreads', '_settraceallthreads', '_stdlib_dir', '_vpath', '_xoptions', 'activate_stack_trampoline', 'addaudithook', 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'copyright', 'deactivate_stack_trampoline', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exception', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'get_int_max_str_digits', 'getallocatedblocks', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getunicodeinternedsize', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'is_stack_trampoline_active', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'monitoring', 'orig_argv', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'platlibdir', 'prefix', 'pycache_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'set_int_max_str_digits', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdlib_module_names', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info', 'warnoptions', 'winver']

要找出内置对象类型提供了哪些属性,可运行dir并传入所需要类型的常量

例如,要查看列表和字符串的属性,可传入空对象。

dir([])
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__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', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

任何内置类型的dir结果都包含了一组属性,这些属性和该类型的实现相关(从技术角度来讲,就是运算符重载的方法)。它们的开头和结尾都是双下划线,从而保证了其独特性。

此外,也可以把类型的名称传给dir(而不是常量),依然可以得到相同的结果。

dir(str) == dir('')
True

dir(list) == dir([])
True

像str和list这类函数以前曾经是类型转换器,而如今实际上已经是Python的类型的名称。调用其中的一个名称,会启用其构造函数,从而产生了该类型的实例。

dir函数可作为记忆提醒器,提供属性名称的列表,但并没有告诉那些名称的意义是什么。

文档字符串:__doc__

除了#注释外,Python也支持可自动附加在对象上的文档,而且在运行时还可保存查看。从语法上来说,这类注释是写成字符串,放在模块文件、函数以及类语句的顶端,就在任何可执行程序代码前(#注释在其之前也没问题)。Python会自动封装这个字符串,也就是成为所谓的文档字符串,使其成为相应对象的__doc__属性

用户定义的文档字符串

例如,下面的文件docstrings.py。其文档字符串出现在文件开端以及其中的函数和类的开头。在这里,文件和函数多行注释使用的是三重引号块字符串,但是任何类型的字符串都能用。

"""
Module documentation
words go here
"""

spam = 40
def square(x):
    """
    function documentation
    square(x)
    """
    return x ** 2

class Employee:
    """
    class documentation
    """
    pass

print(square.__doc__) # function documentatio square(x)
print(Employee.__doc__) # class documentation

文档协议的重点在于,注释会保存在__doc__属性中以供查看(文件导入之后)。因此,要显示这个模块以及其对象打算关联的文档字符串,只需要导入这个文件,简单的打印其__doc__属性(即Python储存文本的地方)即可:

import docstrings

    function documentation
    square(x)
    

    class documentation
    
print(docstrings.__doc__)

Module documentation
words go here

print(docstrings.square.__doc__)

    function documentation
    square(x)
    

一般都需要明确说出要打印的文档字符串;否则会得到嵌有换行字符的单个字符串。

也可以把文档字符串附加到类的方法中,但是因为这些只是嵌套在类中的def语句。要取出模块中类的方法函数的文档字符串,可以通过路径访问类:module.class.method.__doc_

文档字符串标准

文档字符串的文字应该有什么内容,并没有什么标准(不过有些公司有内部标准)。

通常来说,文档在程序员之间的优先级都偏低。而一般情况下,如果你看到文件中有任何注释,那都已经算是幸运了。不过,还是强烈建议你详细的为代码编写文档,这其实是写好代码的重要部分。这里的重点就是,目前文档字符串的结构没有标准。

内置文档字符串

Python中的内置模块和对象都使用类似的技术,在dir返回的属性列表前后加上文档。

例如,要查看内置模块的可读的说明时,可将其导入,并打印其__doc__字符串。

import sys
print(sys.__doc__)
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:    #后面太多了 这里截掉了

内置模块内的函数、类以及方法在其__doc__属性内也有附加的说明信息。

print(sys.getrefcount.__doc__)
Return the reference count of object.

The count returned is generally one higher than you might expect,
because it includes the (temporary) reference as an argument to
getrefcount().

也可以通过文档字符串读取内置函数的说明。

print(sys.getrefcount.__doc__)
Return the reference count of object.

The count returned is generally one higher than you might expect,
because it includes the (temporary) reference as an argument to
getrefcount().

可以用这种方式查看其文档字符串,从而得到内置工具的大量信息

print(int.__doc__)
int([x]) -> 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

PyDoc:help函数

文档字符串技术是实用的工具,Python现在配备了标准PyDoc工具,使其更易于显示。

标准PyDoc工具是Python程序代码,知道如何提取文档字符串并且自动提取其结构化的信息,并将其格式化成各种类型的排列友好的报表。开源领域还有很多其他的工具可以用来提取和格式化文档字符串(包括支持结构化文本的工具,在Web上进行搜索以获得信息),但Python在其标准库中附带了PyDoc。

有很多种方式可以启动PyDoc,包括命令行脚本选项(更多细节请参考Python库手册)。两种最主要的PyDoc接口是内置的help函数和PyDoc GUI/HTML接口。help函数会启用PyDoc从而产生简单的文字报表。

import sys
help(sys.getrefcount)
Help on built-in function getrefcount in module sys:

getrefcount(object, /)
    Return the reference count of object.

    The count returned is generally one higher than you might expect,
    because it includes the (temporary) reference as an argument to
    getrefcount().

注意:调用help时,不是一定要导入sys,但是要取得sys的辅助信息时,就得导入sys,help期待有个对象的引用值传入。

就较大对象而言,诸如,模块和类,help显示内容会分成几段。IDLE3.12.4这里展示一个收缩体(这里不展开了太多行了),点击展开即可。

help(sys)
Help on built-in module sys:

NAME
    sys

MODULE REFERENCE
    https://docs.python.org/3.12/library/sys.html

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known
    path -- module search path; path[0] is the script directory, else ''
    modules -- dictionary of loaded modules

这个报表中的信息有些是文档字符串,而有些(例如,函数调用模式)是PyDoc自动查看对象内部而收集的结构化信息。

也可以对内置函数、方法以及类型使用help。要取得内置类型的help信息,就使用其类型名称(例如,字典为dict,字符串为str,列表为list)。会得到大量的显示内容,说明该类型可用的方法。

help(str.replace)
                                    
Help on method_descriptor:

replace(self, old, new, count=-1, /) unbound builtins.str method
    Return a copy with all occurrences of substring old replaced by new.

      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.

    If the optional argument count is given, only the first count occurrences are
    replaced.

help函数也能用在模块上,就像内置工具一样。

help(docstrings)
Help on module docstrings:

NAME
    docstrings

help(docstrings.square)
Help on function square in module docstrings:

square(x)
    function documentation
    square(x)

PyDoc:HTML报表

想要更宏观的显示的话,PyDoc也提供GUI接口(简单并且可移植的Python/Tkinter脚本),可以将其报表通过HTML网页格式来呈现,可通过任何网页浏览器来查看。在这种模式下,PyDoc可以在本地运行,或者作为客户端/服务器模式中的远程服务器来运行。报表中会包含自动创建的超链接,能够点击应用程序中相关组件的文档。

要通过这种模式启动PyDoc,选择Python 3.12 Module Docs (64-bit),视不同版本而定,但都是module docs。

右上角可以查询、获取对象

选择对象点击即可,这里选择了docstrings对象。

这个网页"Module"部分中的超链接:可以点击这些超链接从而跳到相关(已导入)模块的PyDoc网页。

PyDoc能以许多方式调整和启动。参考Python标准库手册中的内容来了解更多的细节。

PyDoc基本上是“免费”实现报表:如果你善于在文件中使用文档字符串,PyDoc会替你收集信息并排列其格式以便于显示。

PyDoc只能帮助函数和模块这类东西,但是,提供一种简单的方式来读取这类工具的中级文档,其报表比单纯的属性列表更有用,但是,也比不上标准手册那么完整。

标准手册集

为了获得语言以及工具集最新的完整说明,Python标准手册随时可以提供支持。

Python手册以HTML和其他格式来实现,在Windows上是随着Python系统安装:可以从“开始”按钮的Python选单中选取,而且也可以在IDLE的"Help"选项菜单中开启。

也可以从http://www.python.org获得不同格式的手册,或者在该网站上在线阅读(接着Documentation链接)。

在Windows上,手册是编译了的帮助文件,支持搜索,而Python.org的在线版本还包括一个搜索页面。

这里最重要的两个项目是"Library Reference"(说明内置类型、函数、异常以及标准库模块)和"Language Reference"(提供语言层次的细节的官方说明)。这个页面所列的教学文件也为初学者提供了简洁的介绍。

网络资源

在官方的Python程序设计语言网站上(http://www.python.org),你会发现各种Python资源的链接,而其中一些涵盖了特定的主题或领域。点击Documentation链接可以获取在线教程以及"Beginners Guide to Python"。这个网站也列出了非英文的Python资源。

Python博客、菜鸟等等,b站等等视频网站均有资源。

已出版的书籍

可以从大量Python参考书籍中做选择,以作为最终的资源。

书籍会比Python最新的变动慢得多,一部分原因是因为这项工作涉及写作,另部分原因是因为出版的周期原本就比较迟缓。

对多数人而言,专业出版的书籍的方便性和质量,是值得购买的。再者,Python的变动很慢,书籍在出版几年后依然可用,特别是作者还在网站上更新的话。

  • 12
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

兴焉

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

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

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

打赏作者

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

抵扣说明:

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

余额充值