Python——文档

44 篇文章 0 订阅
44 篇文章 21 订阅

python包含了可以使文档的编写变得更简单的语法和工具。

Python文档资源如下表:

形式角色
#注释文件中的文档
dir函数 对象中可用属性的列表
文档字符串:__doc__附加在对象上的文件中的文档
PyDoc:help函数 对象的交互帮助
PyDoc:HTML报表浏览器中的模块文档
标准手册正式的语言和库的说明
网站资源在线教程、例子等
出版的书籍商业参考书籍

====================================================================================

#注释

#字号注释是代码编写文档的最基本的方式。Python会忽略#之后的所有文字(只要#不是位于字符串常量中),不过,这类注释只能从源代码文件中看到。要编写能够更广泛的使用的注释,请使用文档字符串。

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

====================================================================================

dir 函数

内置的dir函数是抓取对象内可用所有属性列表的简单方式(例如,对象的方法以及较简单的数据项)。例如,要找出标准库的sys模块有什么可以用,可将其导入,并传给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', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 
'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 
'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getallocatedblocks', 'getcheckinterval', 
'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 
'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'maxsize', 'maxunicode',
 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'setcheckinterval', 'setprofile',
 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 
'warnoptions', 'winver']
要找出内置对象类型提供了哪些属性,可运行dir并传入所需要类型的常量。例如,要查看列表和字符串的属性,可出入空对象:
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__',
 '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__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']
====================================================================================
文档字符串:__doc__

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

def nslookup(domainName,DNS):
    '''
    get IpAdress for a dominName
    '''
    print('nslookup %s %s'%(domainName,DNS))
    handle = os.popen('nslookup %s %s'%(domainName,DNS),'r')
    result = handle.read()
    if 'UnKnown' in result or 'DNS request timed out' in result:
        return ''
    print('result',result)
    l = result.split('\n')
    l[0:2] = []
    ip = [line.replace('Address:','').replace('Addresses:','').strip() for line in l if 'Address' in line][0]
    return ip

-----------------------------------------------------------------------------------------------------------------------------------------------

文档字符串标准
文档字符串的文字应该有什么内容,并没有什么标准(不过有些公司有内部标准),如果你想用,就别犹豫。建议详细地为代码编写文档。

-----------------------------------------------------------------------------------------------------------------------------------------------

内置文档字符串

Python中的内置模块和对象都使用类似的技术,在dir返回的属性列表前后加上文档。例如,要查看内置模块的可读的说明时,可将其导入,并打印其__doc__字符串

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

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
#...more text omitted...
内置模块内的函数、类以及方法在其__doc__属性内也有附加的说明信息:

>>> print(sys.getprofile.__doc__)
getprofile()

Return the profiling function set with sys.setprofile.
See the profiler chapter in the library manual.
也可以通过文档字符串读取内置函数的说明:
>>> print(int.__doc__)
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
可以用这种方法查看其文档字符串,从而得到内置工具的大量信息,但是你不必这样做:下面的help函数会为你自动做这件事
============================================================== ======================

PyDoc:help函数

文档字符串技术是使用的工具,Python现在配备了一个工具,使其更易于显示。便准PyDoc工具是Python程序代码,知道如何提取文档字符串并且自动提取其结构化的信息,并将其格式化成各种类型的排列友好的报表。

有很多种方式可以启动PyDoc,包括命令行脚本选项。也许两种最主要的PyDoc接口是内置的help函数和PyDoc GUI/HTML接口。

help函数会启动PyDoc从而产生简单的文字报表:

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

getrefcount(...)
    getrefcount(object) -> integer
    
    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显示内容会分成几段,而其中有一些会在这里显示。通过交互模式运行它,来查看完整的报表:
>>> help(sys)
Help on built-in module sys:

NAME
    sys

MODULE REFERENCE
    http://docs.python.org/3.4/library/sys
    
    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:
#...more text omitted...
这个报表中的信息有些事文档字符串,有些事PyDoc自动查看对象内部而收集的结构化信息。你也可以对内置函数、方法以及类型使用help
>>> help(dict)
Help on class dict in module builtins:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v

# ...more text omitted...
============================================================== ======================
PyDoc:HTML报表

在交互模式下工作时,help函数是获取文档的好帮手。然而,想要更宏观的显示的话,PyDoc也提供GUI接口,可以将其报表通过HTML网页格式来呈现。

====================================================================================

标准手册集

Python手册以HTML和其他格式来实现,在Windows上是随着Python系统安装:可以从“开始”按钮的Python选单中选取,而且也可以在IDLE的“Help”选项菜单中开启。也可以从http://www.python.ort获得不同格式的手册,或者在该网站上在线阅读。
在Windows上,手册是编译了的帮助文件,支持搜索。

Python 是一种易于学习又功能强大的编程语言。它提供了高效的高级数据结构,还有简单有效的面向对象编程。Python 优雅的语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本和快速开发应用的理想语言。 Python 解释器及丰富的标准库以源码或机器码的形式提供,可以到 Python 官网 https://www.python.org/ 免费获取适用于各个主要系统平台的版本,并可自由地分发。这个网站还包含许多免费第三方 Python 模块、程序和工具以及附加文档的发布页面或链接。 Python 解释器易于扩展,可以使用 C 或 C++(或者其他可以通过 C 调用的语言)扩展新的功能和数据类型。Python 也可用于可定制化软件中的扩展程序语言。 这个教程非正式地介绍 Python 语言和系统的基本概念和功能。最好在阅读的时候准备一个 Python 解释器进行练习,不过所有的例子都是相互独立的,所以这个教程也可以离线阅读。 有关标准的对象和模块,参阅 Python 标准库。Python 语言参考 提供了更正式的语言参考。想要编写 C 或者 C++ 扩展可以参考 扩展和嵌入 Python 解释器 和 Python/C API 参考手册。也有不少书籍深入讲解Python 。 这个教程并没有完整包含每一个功能,甚至常用功能可能也没有全部涉及。这个教程只介绍 Python 中最值得注意的功能,也会让你体会到这个语言的风格特色。学习完这个教程,你将可以阅读和编写 Python 模块和程序,也可以开始学习更多的 Python 库模块,详见 Python 标准库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值