Link to class method in python docstring

。_饼干妹妹 提交于 2019-12-03 06:26:38

问题


I want to add a link to a method in my class from within the docstring of another method of the same class. I want the link to work in sphinx and preferentially also in Spyder and other Python IDE's.

I tried several options and found only one that works, but it's cumbersome.

Suppose the following structure in mymodule.py

def class MyClass():
    def foo(self):
        print 'foo'
    def bar(self):
        """This method does the same as <link to foo>"""
        print 'foo'

I tried the following options for <link to foo>:

  • :func:`foo`
  • :func:`self.foo`
  • :func:`MyClass.foo`
  • :func:`mymodule.MyClass.foo`

The only one that effectively produces a link is :func:`mymodule.MyClass.foo`, but the link is shown as mymodule.MyClass.foo() and I want a link that is shown as foo() or foo.
None of the options above produces a link in Spyder.

Thanks for your help.


回答1:


The solution that works for Sphinx is to prefix the reference with ~.

Per the Sphinx documentation on Cross-referencing Syntax,

If you prefix the content with ~, the link text will only be the last component of the target. For example, :py:meth:~Queue.Queue.get will refer to Queue.Queue.get but only display get as the link text.

So the answer is:

class MyClass():
    def foo(self):
        print 'foo'
    def bar(self):
        """This method does the same as :func:`~mymodule.MyClass.foo`"""
        print 'foo'

This results in an html looking like this : This method does the same as foo(), and foo() is a link.

However, note that this may not display in Spyder as a link.




回答2:


If you want to manually specify the text of the link you can use:

:func:`my text <mymodule.MyClass.foo>`

For more information, checkout Cross-referencing Python objects.




回答3:


It seems to me that you just have to add __name__ or __doc__ to your expression to obtain what you want.
I'm still not sure to have correctly understood the aim

class MyClass():
    def foo(self):
        """I am the docstring of foo"""
        print 'foo'
    def bar(self):
        """This method does the same as <link to foo>"""
        print 'foo'

print
print MyClass.foo
print MyClass.foo.__name__
print MyClass.foo.__doc__
print
print MyClass.__dict__['foo']
print MyClass.__dict__['foo'].__name__
print MyClass.__dict__['foo'].__doc__

result

<unbound method MyClass.foo>
foo
I am the docstring of foo

<function foo at 0x011C27B0>
foo
I am the docstring of foo


来源:https://stackoverflow.com/questions/21289806/link-to-class-method-in-python-docstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!