简体   繁体   中英

Cross reference documentation of function or class in Sphinx for Python

I want, within an explanatory documentation, a reference to the documentation of a Python class and, a little later, to its constructor. So imagine there is a file

# MyLib/MyClass.py
class MyClass:
    """Class Introduction"""
    def __init__(paramX):
        """:param paramX: Xes out things"""

and my rst file

#MyLib/docs/source/MyDoc.rst
Some text where :ref:`here` is my reference to "Class Introduction"
 and :ref:`there` follows my reference to the __init__ method documentation

How can I get the reference working: How and where within the Sphinx files do I need to include the Python file and how do I define (in the Python file) and resolve (in the rst file) the references? The expected output would be something like this:

Some text where <link to documentation of class _MyClass_>...
 and 
    'class MyClass
        def __init__(paramX):
           paramX: Xes out things'

where as described the brackets <..> include a link to the documentation and the documentation itself appears after the 'and', referenced in the rst file by :ref:`here` and :ref:`there` , respectively.

From the example in the question the module ref_constructor.py

class MyClass:
    """Class Introduction."""
    def __init__(paramX):
        """The docstring of constructor.

        :param paramX: Xes out things.
        :type paramX: str
        """

Using the reST file ref_constructor.rst take care to choose the adequate roles, in this case :class: and :meth:

Reference to class constructor
------------------------------

.. automodule:: ref_constructor


.. here begins de documentation.

Some text where :class:`ref_constructor.MyClass` is my reference to "Class Introduction"
and :meth:`ref_constructor.MyClass.__init__` follows my reference to the __init__ method documentation.


Some text where :class:`MyClass` is my reference to "Class Introduction"
and :meth:`MyClass.__init__` follows my reference to the __init__ method documentation.

You can write the cross-references using fully qualified names or a shortened forms depending on context

Cross-referencing Python objects

The name enclosed in this markup can include a module name and/or a class name. For example, :py:func:`filter` could refer to a function named filter in the current module, or the built-in function of that name. In contrast, :py:func:`foo.filter` clearly refers to the filter function in the foo module.

The result

HTML 生成文档的屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM