如何使用sphinx和autodoc记录“子类”?

1 投票
1 回答
1245 浏览
提问于 2025-04-17 21:47

假设我有一个文件叫做 example.py,里面的内容是:

class Body(object):
    """Representation of a geometric body."""
    def __init__(self):
        self.surface = Surface(self)

class Surface(object):
    """Representation of a geometric surface."""
    def __init__(self, body):
        self.body = body

    def get_surface_area(self):
        """ Calculate surface area of the body """
        print 4

mybody = Body()
mybody.surface.get_surface_area()

当我执行

.. automodule:: example
    :members:

这时我能看到所有两个类和一个函数的文档说明。不过,我该怎么做才能清楚地说明我的类的使用方法,比如 mybody.surface.get_surface_area(),并且确保链接是正确的呢?

1 个回答

1

我不太确定这是否是你想要的,但我可以给你一个建议,关于如何记录你的类:

class Body(object):
    """Representation of a geometric body.

      :ivar surface: a :class:`example.Surface` instance 

      Usage example:

      >>> mybody = Body()
      >>> mybody.surface.get_surface_area()
      >>> 4

      Another way of doing it:

      >>> mybody = Body()
      >>> mysurface = Surface(mybody)
      >>> mysurface.get_surface_area()
      >>> 4

    """
    def __init__(self):
        self.surface = Surface(self)  

class Surface(object):
    """Representation of a geometric surface.

     :ivar body: The supplied :class:`example.Body` instance

    """
    def __init__(self, body):
        self.body = body             

    def get_surface_area(self):
        """ Calculate surface area of the body """
        print 4

撰写回答