# This is a learning note for the Liaoche teacher Python tutorial
1 , overview
Write the specification's comment code in the document. Python's built-in document Test (doctest) module can extract the code directly from the comments and perform the test.
1.1 , to ABS () function as an example:
# abs.py
def ABS (n):
''' # Two for a pair, newline input
Function to get absolute value of number. # a simple introduction
Example:
>>> ABS (1) # test
1
>>> ABS (-1)
1
>>> ABS (0)
0
''' #
return n if n >= 0 else (-N) # function Body
$ python ABS. py # command-line executor, no return value, the code is correct
1.2 , doctest to test the last written Dict class
# mydict2.py
Class Dict (Dict):
'''
Simple Dict-also support access as x.y style.
>>> D1 = Dict ()
>>> d1[' x '] = 100
>>> d1.x
100
>>> D1.Y = 200
>>> d1[' y ']
200
>>> D2 = Dict (A=1, b=2, c= ' 3 ')
>>> d2.c
' 3 '
>>> d2[' empty ']
Traceback (most recent):
... # of these three . represents a large segment of output
Keyerror: ' Empty '
>>> D2.empty
Traceback (most recent):
...
Attributeerror: ' Dict ' object has no attribute ' empty '
'''
def __init__ (self, **kw):
Super (Dict, self). __init__ (**KW)
def __getattr__ (self, key):
Try
return Self[key]
Except Keyerror:
Raise Attributeerror (R "' Dict ' object has no attribute '%s '"% key)
def __setattr__ (self, Key, value):
Self[key] = value
If __name__== ' __main__ ':
Import Doctest
Doctest.testmod ()
Summarize:
Doctest is very useful, not only for testing, but also for direct example code. With some document generation tools, you can automatically extract comments that contain doctest. When users look at the document, they also see the doctest.
Python Learning note __8.4 document testing