سؤال

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
هل كانت مفيدة؟

المحلول

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__()
    ...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top