python入门系列第十五篇: 文档

181 阅读2分钟
原文链接: zhuanlan.zhihu.com

本章节主要讲述如何编写python代码的文档的技术与工具。

常见的python文档资源


# 注释 -- 文件中的文档
dir函数 -- 对象中可用属性的列表
文档字符串: __doc__  -- 附加在对象上的文件中的文档
pyDoc: help函数  -- 对象的交互文档
pyDoc: HTML报表 -- 浏览器中的模块文件
标准手册: 语言说明与文档说明


注释

#字号注释是代码编写文档的最基本的方式。这类注释只能在源代码文件中看到,如果要编写更广泛使用的注释,推荐使用文档字符串。


文档字符串: 适用于较大型功能的文档
#注释: 适用于较小功能的文档


dir函数

内置的dir函数会抓取对象内可用所有属性列表。

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']
>>>


>>> dir('')
['__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', '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('') == dir(str)
True
>>>


dir函数可以作为记忆提醒器, 提供属性名称的列表。


文档字符串: __doc__

除了#注释外, python还支持可自动附加在对象上的文档, 从语法上看, 这类注释写成字符串, 放在模块文件, 函数, 类语句的顶端。 就在任何可执行代码前。python会自动封装这个字符串, 即成为文档字符串, 并使其成为相应对象的_doc__属性。


# 用户定义的文档字符串

"""
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


# 内置文档字符串: python的一些内置模块与对象都有类似的文档.

>>> import sys
>>> print(sys.__doc__)


pyDoc: help函数


import sys
help(sys.exit)
help(str)

help()期待传入一个对象的引用, 就较大的对象而言如模块与类, help显示内容会分为几段, 默认只显示一部分, 其他通过交互显示。


常见的python代码的陷阱
  • 不要忘记冒号
  • 代码从第一行开始
  • 缩进要保持一致
  • 使用简单的for循环, 而不是while循环与range
  • 注意赋值语句中的可变对象
  • 一定要使用括号调用函数
  • 不要期待在原处修改对象的函数会返回结果
  • 不要在导入和重载中使用扩展名或者路径