【问题标题】:What's the difference in behaviour between :func: and :meth: roles in Python Sphinx?Python Sphinx 中的 :func: 和 :meth: 角色之间的行为有什么区别?
【发布时间】:2016-01-18 06:10:33
【问题描述】:

http://www.sphinx-doc.org/en/stable/domains.html#cross-referencing-python-objects 的 Sphinx 文档说,

:py:func: 引用一个 Python 函数;可以使用带点的名称。角色文本不需要包括尾括号以增强可读性; 它们将由 Sphinx 自动添加,如果 add_function_parentheses 配置值为 True(默认)。

:py:meth: 引用对象的方法。角色文本可以包括类型名和方法名;如果它发生在描述中 一个类型,类型名称可以省略。可以使用带点的名称。

但我找不到他们的行为方式有什么不同。

这是我为其生成文档的 Python 模块。

"""foo module."""

def hello(name):
    """Print hello addressed to *name*.
    
    Args:
      name (str): Name to address.
    """
    print('hello', name)

class Foo:

    """Foo class."""

    def bye(self, name):
        """Print bye addressed to *name*.

        Args:
          name (str): Name to address.
        """
        print('bye', name)

if __name__ == '__main__':
    hello('world')
    Foo().bye('python')

这是我在index.rst 文件中的内容。

Foo Documentation
=================

See :func:`foo.hello` and :func:`foo.Foo.bye`.

Also, see :meth:`foo.hello` and :meth:`foo.Foo.bye`.

foo module
==========
.. automodule:: foo
    :members:

执行make html 后,这是我看到的输出。

:func::meth: 角色都生成了到 helloFoo.bye 的有效交叉引用超链接,无论目标是函数还是方法。

那么:func::meth: 角色之间的区别是什么。你能举一个他们表现不同的例子吗?

【问题讨论】:

    标签: python python-sphinx cross-reference


    【解决方案1】:

    我查看了 Sphinx 代码。我能够辨别的唯一区别是每个角色都生成 HTML 元素,其 HTML class 包含创建它的角色的名称。例如,:func: 角色的 code 元素将如下所示:

    <code class="xref py py-func docutils literal">
    

    而对于:meth: 角色,它将具有py-meth 而不是py-func。 Sphinx 中包含的普通 CSS 样式不区分 py-methpy-func,但可以使用不同样式的样式表。

    为了好玩,我尝试了其他角色(例如class)并让它们指向对象上的方法。即使没有意义,Sphinx 也没有问题。

    【讨论】:

      【解决方案2】:

      就功能而言,至少有一个区别。

      每当你使用 autoclass 语法(. 在类名前面)时,自动解析完整的类名:

      • :meth:`.myClass` 将搜索范围限制为当前模块。
      • :func:`.myClass` 还解析外部类。

      【讨论】:

        【解决方案3】:

        它是在生成的索引中使用的语义信息,例如将某物标记为函数或方法。正如 Louis 已经提到的,可以通过 CSS 在 HTML 中为它们设置不同的样式。

        【讨论】:

          猜你喜欢
          • 2011-04-16
          • 1970-01-01
          • 2018-05-01
          • 1970-01-01
          • 2021-10-15
          • 1970-01-01
          • 1970-01-01
          • 2011-02-09
          相关资源
          最近更新 更多