Dmy*_*kyi 7 python python-sphinx callable-object
我研究了这个主题,但找不到明确的解决方案。有一个类似的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)
Run Code Online (Sandbox Code Playgroud)
这大约相当于这个(远不准确):
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)
Run Code Online (Sandbox Code Playgroud)
最新的情况很明显,我可以使用文档字符串和Sphinxdo 来记录每个方法:
.. autoclass:: package.Casting
:members:
.. automethod:: __init__(self, int_converter_function, float_converter_function)
Run Code Online (Sandbox Code Playgroud)
如何对注释进行同样的操作?
更新:
我发现我的问题应该更具体。我想要
从文档中完全删除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')
"""
Run Code Online (Sandbox Code Playgroud)
更新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)
Run Code Online (Sandbox Code Playgroud)
我想package.casting.dataclass从文档中删除。