Sam*_*ufi 5 python inheritance restructuredtext python-sphinx
我有一些相互继承的类。所有类都包含相同的方法(让我们称之为mymethod),由此子类覆盖基类方法。我想mymethod使用sphinx为所有类生成文档。
假设mymethod接受一个论点myargument。此参数对于基方法和继承方法具有相同的类型和含义。为了尽量减少冗余,我myargument只想为基类编写文档,并将文档插入子方法的文档中。也就是说,我不想只对基类进行简单的引用,而是在生成文档时动态插入文本。
这能做到吗?如何?
请在下面找到一些说明问题的代码。
class BaseClass
def mymethod(myargument):
"""This does something
Params
------
myargument : int
Description of the argument
"""
[...]
class MyClass1(BaseClass):
def mymethod(myargument):
"""This does something
Params
------
[here I would like to insert in the description of ``myargument`` from ``BaseClass.mymethod``]
"""
BaseClass.mymethod(myargument)
[...]
class MyClass2(BaseClass):
def mymethod(myargument, argument2):
"""This does something
Params
------
[here I would like to insert in the description of ``myargument`` in ``BaseClass.mymethod``]
argument2 : int
Description of the additional argument
"""
BaseClass.mymethod(argument)
[...]
Run Code Online (Sandbox Code Playgroud)
可能并不理想,但也许您可以使用装饰器来扩展文档字符串。例如:
class extend_docstring:
def __init__(self, method):
self.doc = method.__doc__
def __call__(self, function):
if self.doc is not None:
doc = function.__doc__
function.__doc__ = self.doc
if doc is not None:
function.__doc__ += doc
return function
class BaseClass:
def mymethod(myargument):
"""This does something
Params
------
myargument : int
Description of the argument
"""
[...]
class MyClass1(BaseClass):
@extend_docstring(BaseClass.mymethod)
def mymethod(myargument):
BaseClass.mymethod(myargument)
[...]
class MyClass2(BaseClass):
@extend_docstring(MyClass1.mymethod)
def mymethod(myargument, argument2):
"""argument2 : int
Description of the additional argument
"""
BaseClass.mymethod(argument)
[...]
print('---BaseClass.mymethod---')
print(BaseClass.mymethod.__doc__)
print('---MyClass1.mymethod---')
print(MyClass1.mymethod.__doc__)
print('---MyClass2.mymethod---')
print(MyClass2.mymethod.__doc__)
Run Code Online (Sandbox Code Playgroud)
结果:
---BaseClass.mymethod---
This does something
Params
------
myargument : int
Description of the argument
---MyClass1.mymethod---
This does something
Params
------
myargument : int
Description of the argument
---MyClass2.mymethod---
This does something
Params
------
myargument : int
Description of the argument
argument2 : int
Description of the additional argument
Run Code Online (Sandbox Code Playgroud)
如果您将装饰器设置为描述符并在其中搜索它,则可以动态解析覆盖方法,__get__但这意味着装饰器不再可堆叠,因为它不返回真正的函数。