Home  >  Article  >  Backend Development  >  Python study notes - writing help documents for custom classes or functions, and conducting document testing

Python study notes - writing help documents for custom classes or functions, and conducting document testing

黄舟
黄舟Original
2017-01-17 14:27:061923browse

In python we can use help("module name") or help(class name) to view the documentation of a class or function. But how are they written? In fact, they use """ three double quotes to wrap multiple lines of comments at the beginning of the class or the method. These contents will be regarded as help documents by Python.


What content is generally written in the help document? It mainly includes the following content:


##The main function of this class or function


##Incoming values ​​and output values


Instructions for some special situations


Document test content


The above content is a personal summary, but I have not seen relevant information


Let’s give an example:

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

Enter

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

Use doctest for document testing in the python terminal


We can also use the doctest module for document testing in the comments.

#For example, after we add the document test content, it looks like this:

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()

Because we wrote

if __name__ == '__main__':
import doctest
doctest.testmod()

So the above document test will only be performed when executing with the entry file, so it will not be executed in actual application.

## The above are the python study notes - writing help documents for custom classes or functions, and document testing. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)


#! ##

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn