狮身人面像装饰 类 未记录

Sphinx decorated classes not documented

我正在用 Sphinx 记录我的图书馆。我有装饰器 logic_object:

class logic_object:
    """Decorator for logic object class.
    """
    def __init__(self, cls):
        self.cls = cls
        self.__doc__ = self.cls.__doc__

我有 gravity class 由 logic_object:

装饰
@logic_object
class gravity:
    """Basic gravity object logic class.

    :param float g: pixels of acceleration
    :param float jf: jump force
    """
#There is more not important code.

我的 Sphinx .rst 文件是:

Mind.Existence
========================
Classes, methods and functions marked with * aren't for usual cases, they are made to help to the rest of the library.

.. automodule:: Mind.Existence
   :members:
   :member-order: bysource

logic_objectautodoc 记录,但 gravity 没有。

为什么会发生这种情况以及如何解决?

这是因为修饰的class不是真正的class对象(不是type的实例),因此autodoc不知道如何记录它。

要修复它,您必须编写自定义文档(例如,在您的 conf.py 中):

from Mind.Existence import logic_object
from sphinx.ext.autodoc import ClassDocumenter

class MyClassDocumenter(ClassDocumenter):
    objtype = 'logic_object'
    directivetype = 'class'

    @classmethod
    def can_document_member(cls, member, membername, isattr, parent):
        return isinstance(member, logic_object)

def setup(app):
    app.add_autodocumenter(MyClassDocumenter)

然后(在你的装饰器中)你还必须从装饰对象中复制 __name____bases__::

def __init__(self, cls):
    self.cls = cls
    self.__doc__ = cls.__doc__
    self.__name__ = cls.__name__
    self.__bases__ = cls.__bases__

HTH, 吕克