简体   繁体   English

Python:如何在doctest中定义类?

[英]Python: How can I define a class in a doctest?

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. 我想使用doctest注释块来演示特定基类的用法,但要么这不能用doctest完成,要么我做错了。 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不完整,直到你有一个空的...延续行:

    >>> class A(MyClass):
    ...     def __init__(self):
    ...         super(A, self).__init__()
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM