python学习笔记-为自定义类或者函数编写help文档,以及进行文档测试

黄舟
发布: 2017-01-17 14:27:06
原创
2269人浏览过

python中我们可以利用help("模块名")或者help(类名)的方式来查看类或者函数的文档。但是它们是如何编写的呢?其实它们在类最前面或者方法的最前面用"""三个双引号包裹了多行注释。这些内容就会被python当成帮助文档。

那帮助文档一般会写什么内容呢?主要包括以下内容:

该类或者函数的主要作用

传入的值和输出的值

一些特殊情况的说明

立即学习Python免费学习笔记(深入)”;

文档测试内容

以上内容是个人的总结,但是并没有看到相关的资料。

我们来举一个例子:

class Apple(object):
""" This is an Apple Class"""
def get_color(self):
"""
Get the Color of Apple.
get_color(self) -> str
"""
return "red"
登录后复制

在python terminal输入

夸克文档
夸克文档

夸克文档智能创作工具,支持AI写作/AIPPT/AI简历/AI搜索等

夸克文档 484
查看详情 夸克文档
>>> from CallDemo import Apple
>>> help(Apple)
Help on class Apple in module CallDemo:
class Apple(__builtin__.object)
| This is an Apple Class
| 
 | Methods defined here:
| 
 | get_color(self)
| Get the Color of Apple.
| get_color(self) -> str
| 
 | ----------------------------------------------------------------------
| Data descriptors defined here:
| 
 | __dict__
| dictionary for instance variables (if defined)
| 
 | __weakref__
| list of weak references to the object (if defined)
登录后复制

利用doctest进行文档测试

我们在注释中我们也可以doctest模块进行文档测试。

例如,我们添加了文档测试内容后如下所示:

class Apple(object):
"""
This is an Apple Class
Example:
>>> apple = Apple()
>>> apple.get_color()
'red'
>>> apple.set_count(20)
>>> apple.get_count()
400
"""
def get_color(self):
"""
Get the Color of Apple.
get_color(self) -> str
"""
return "red"
def set_count(self, count):
self._count = count
def get_count(self):
return self._count * self._countif __name__ == '__main__':
import doctest
登录后复制

doctest.testmod()

由于我们写了

if __name__ == '__main__':
import doctest
doctest.testmod()
登录后复制

所以以上文档测试只有在以入口文件执行的时候才会进行文档测试。因此并不会在实际应用在执行文档测试。

以上就是python学习笔记-为自定义类或者函数编写help文档,以及进行文档测试的内容,更多相关内容请关注PHP中文网(www.php.cn)!

相关标签:
python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号