简体   繁体   English

Sphinx:链接到 Python 文档字符串中另一个模块中的类的方法

[英]Sphinx: Link to a method of a class in another module in Python docstring

I want to add a link to a method of a class in one module (say module_2.py ) in another method in another module ( say module_1.py ).我想添加一个模块(比如在一个链接到一个类的方法module_2.py在另一模块(比如另一种方法) module_1.py )。 I want the link to work in Sphinx.我希望链接在 Sphinx 中工作。

Suppose:假设:

module_1.py模块_1.py

class ABC:
   def foo(self):
      """
      See docstring of module_2.py bar():<link to bar() in module_2.py>
      """
      print("foo")

module_2.py模块_2.py

class XYZ:
    def bar(self):
    """
    This function prints hello.
    """
    print("hello")

You can write:你可以写:

class ABC:
  def foo(self):
    """
    See docstring of :py:meth:`bar() <XYZ.bar>` in :py:mod:`module_2`.
    """
    print("foo")

The shown markup uses a role to link to a documented element.显示的标记使用角色链接到文档元素。 If Python is the default domain for your documentation, then :py can be omitted.如果 Python 是文档的默认域,则:py可以省略。 The role meth links to a method name.角色meth链接到方法名称。 A dotted name can be used.可以使用带点的名称。 Likewise, mod links to a module name.同样, mod链接到模块名称。 The content of a role is written wetween `` .角色的内容写成ween `` The content (logical link name can have a differnet visual content. Therefore the logical link name is written in <> . Example: :role:`text <logical name>` .内容(逻辑链接名称可以有不同的视觉内容。因此逻辑链接名称写在<> 。例如: :role:`text <logical name>`

Further information: http://www.sphinx-doc.org/en/stable/domains.html#role-py:meth更多信息: http : //www.sphinx-doc.org/en/stable/domains.html#role-py : meth

To truly get a hyperlink, your method reference needs to contain a complete path.要真正获得超链接,您的方法引用需要包含完整路径。 The simplest way to create any link is using the :obj: cross-reference:创建任何链接的最简单方法是使用:obj:交叉引用:

"""See docstring of :obj:`path.to.module_2.XYZ.bar`."""

See docstring of path.to.module_2.XYZ.bar .请参阅path.to.module_2.XYZ.bar文档字符串。

You can shorten the anchor text to just the last element of the path with the tild ~ :您可以使用波浪号将锚文本缩短为路径的最后一个元素~

"""See docstring of :obj:`~path.to.module_2.XYZ.bar`."""

See docstring of bar .请参阅bar文档字符串。

Or specify custom text like so:或者像这样指定自定义文本

"""See docstring of :obj:`XYZ.bar <path.to.module_2.XYZ.bar>`."""

See docstring of XYZ.bar .请参阅XYZ.bar文档字符串。

This is perhaps the most reader-friendly solution.这可能是对读者最友好的解决方案。

For completeness, note that :obj: is a general untyped reference, but Sphinx provides several other categories of cross-reference with some specific behaviours.为了完整:obj: ,请注意:obj:是一个通用的无类型引用,但 Sphinx 提供了其他几种具有某些特定行为的交叉引用类别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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