我研究了这个主题,但看不到明确的解决方案。有一个类似的SO问题
我的问题是我有一个带有注释的类attr.dataclass
,typing_extensions.final
我不希望它们被记录,但我仍然想从如何调用该类的角度来描述它。
例如,
@final
@dataclass(frozen=True, slots=True)
class Casting(object):
_int_converter_function = int
_float_converter_function = float
def __call__(self, casting, value_to_cast):
if casting['type'] == 'integer':
return self._int_converter_function(value_to_cast)
return self._float_converter_function(value_to_cast)
这大约相当于这个(远非准确):
class Casting(object):
def __init__(
self,
int_converter_function = int,
float_converter_function = float,
):
self.int_converter_function = int_converter_function
self.float_converter_function = float_converter_function
def converter(self, casting, value):
self.value = value
yield
type = casting['type']
if type == 'integer':
yield self.int_converter_function(value)
else:
yield self.float_converter_function(value)
并且最新的很明显,我可以用文档字符串记录每个方法并在Sphinx
做:
.. autoclass:: package.Casting
:members:
.. automethod:: __init__(self, int_converter_function, float_converter_function)
如何对注释做同样的事情?
更新:
我发现我的问题应该更具体。我想要
从文档中完全消除
dataclass
,但仍然将类保留在文档中。它把课程弄得一团糟,以至于文档不可读。在 上创建一个文档字符串,
__init__
但也要将其与可调用描述分开。我留下了评论。
文档示例:
"""Cast one type of code to another.
Constructor arguments:
:param int_converter_function: function to convert to int
:param float_converter_function: function to convert to float
Callable arguments:
:param casting: :term:`casting` object
:type casting: dict
:param value_to_cast: input value
:return: Casted value
Example
>>> cast = Casting(int)
>>> cast({'type': 'integer'}, '123')
123
>>> cast({'type': 'decimal'}, '123.12')
Decimal('123.12')
"""
更新 2:
完整的课程如下:
# -*- coding: utf-8 -*-
from attr import dataclass
from typing_extensions import final
@final
@dataclass(frozen=True, slots=True)
class Casting(object):
"""Cast one type of code to another.
Constructor arguments:
:param int_converter_function: function to convert to int
:param float_converter_function: function to convert to float
Callable arguments:
:param casting: :term:`casting` object
:type casting: dict
:param value_to_cast: input value
:return: Casted value
Example
>>> cast = Casting(int)
>>> cast({'type': 'integer'}, '123')
123
>>> cast({'type': 'decimal'}, '123.12')
Decimal('123.12')
"""
_int_converter_function = int
_float_converter_function = float
def __call__(self, casting, value_to_cast):
if casting['type'] == 'integer':
return self._int_converter_function(value_to_cast)
return self._float_converter_function(value_to_cast)
我想package.casting.dataclass
从文档中删除。