【问题标题】:python-2.7: doctests ignored in setter method of a classpython-2.7:类的setter方法中忽略的doctests
【发布时间】:2014-06-14 00:00:48
【问题描述】:

为什么下面的示例在 setter 方法中运行它的 doctest 失败?

class Foo:
    a = None

    @property
    def a(self):
        pass

    @a.setter
    def a(self, v):
        '''
        >>> 1 == 1
        False
        '''
        pass

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

调试器确认没有运行测试(上面的示例写入dtest.py):

>>> import dtest, doctest
>>> doctest.testmod(dtest)
TestResults(failed=0, attempted=0)

getter方法中同样的测试正确执行,当然报失败了……

【问题讨论】:

    标签: python python-2.7 properties setter doctest


    【解决方案1】:

    @a.setter 装饰器会忽略文档字符串,并且不会将其复制到生成的 property 对象中;而是在 getter 上设置文档字符串。

    property documentation

    如果给定,doc 将是属性属性的文档字符串。否则,属性将复制 fget 的文档字符串(如果存在)。

    强调我的。

    您的代码导致:

    >>> class Foo:
    ...     a = None
    ...     @property
    ...     def a(self):
    ...         pass
    ...     @a.setter
    ...     def a(self, v):
    ...         '''
    ...         >>> 1 == 1
    ...         False
    ...         '''
    ...         pass
    ...
    >>> Foo.a
    <property object at 0x101a21050>
    >>> Foo.a.__doc__ is None
    True
    

    getter 上设置文档字符串,然后你会得到:

    >>> class Foo:
    ...     a = None
    ...     @property
    ...     def a(self):
    ...         '''
    ...         >>> 1 == 1
    ...         False
    ...         '''
    ...         pass
    ...     @a.setter
    ...     def a(self, v):
    ...         pass
    ... 
    >>> Foo.a
    <property object at 0x101a210a8>
    >>> Foo.a.__doc__
    '\n        >>> 1 == 1\n        False\n        '
    

    另一个丑陋的解决方法是使用从 setter 复制的文档字符串重新创建属性,显式:

    class Foo:
        a = None
    
        @property
        def a(self):
            pass
    
        @a.setter
        def a(self, v):
            '''
            >>> 1 == 1
            False
            '''
            pass
    
        a = property(a.fget, a.fset, doc=a.fset.__doc__)
    

    【讨论】:

    • 我明白了。为了完整起见,您能否添加任何参考来解释基本原理、正确用法等? [官方文档] (docs.python.org/2.7/library/doctest.html) 没有提供更多信息。
    • @sphakka:确实如此;我引用了相关部分。
    猜你喜欢
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    相关资源
    最近更新 更多