Python: How can I define a class in a doctest?

2019-04-20 22:40发布

I would like to use a doctest comment block to demonstrate the usage of a particular base class, but either this cannot be done with doctest or I am doing something wrong. Here is my simple demo code.

class MyClass(object):
    '''
    >>> m = MyClass()
    >>> print m.x
    1
    >>> class A(MyClass):
    >>>  def __init__(self):
    >>>    super(A,self).__init__()
    >>>
    >>> a = A()
    >>> print a.x
    1
    '''


    def __init__(self):
        self.x = 1


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

The code doesn't run. Here's the first error issued:

Failed example:
class A(MyClass):
Exception raised:
Traceback (most recent call last):
  File "C:\Python27\lib\doctest.py", line 1254, in __run
    compileflags, 1) in test.globs
  File "<doctest __main__.MyClass[2]>", line 1
    class A(MyClass):
                    ^
SyntaxError: unexpected EOF while parsing

1条回答
时光不老,我们不散
2楼-- · 2019-04-20 23:01

Try it out in the interpreter; it uses ... to show continuation lines. >>> is only for a new statement or expression, while a class in incomplete until you've had an empty ... continuation line:

    >>> class A(MyClass):
    ...     def __init__(self):
    ...         super(A, self).__init__()
    ...
查看更多
登录 后发表回答