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

笑着哭i 提交于 2019-12-06 19:56:38

问题


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:


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


来源:https://stackoverflow.com/questions/13510698/python-how-can-i-define-a-class-in-a-doctest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!