首页 > 解决方案 > Python:指定类型的文档属性

问题描述

让我们考虑以下示例:

from typing import Union
import numpy as np

class MyClass:
    def __init__(self):
        self._x = None
        
    @property
    def x(self) -> Union[float, np.ndarray]:
        if len(self._x) == 1:
            return self._x[0]
        else:
            return self._x
    
    @x.setter
    def x(self, value: Union[float, list, np.ndarray]):
        self._x = np.atleast_1d(value)

关于如何正确记录上述代码的任何建议?我正在使用Sphinxnumpydoc

非常感谢!

编辑:我意识到我的问题不是很清楚,所以我要补充几句。x基本上,主要问题是如何记录作为float, list or array输入和输出的事实float or array。我在一些例子中看到这应该是getter唯一的,我不知道我是否应该添加关键字ParametersReturns或者它是否是更好的方法,因为我没有找到足够的答案(或者我只是想念他们)。

标签: python-3.xpython-sphinxpython-typingdocstringnumpydoc

解决方案


您可以__doc__在最终属性上显式分配属性,例如:

class MyClass:
    def __init__(self):
        self._x = None
        
    @property
    def x(self) -> Union[float, np.ndarray]:
        ...
    
    @x.setter
    def x(self, value: Union[float, list, np.ndarray]):
        ...

    x.__doc__ = """\
                 Documentation text goes here.
                 (you may want to call textwrap.dedent on this string)

                """

推荐阅读