2016-11-09 39 views
4

编辑“继承”方法的文档: 截至目前(狮身人面像1.4.9)似乎有没有办法告诉狮身人面像做什么我想(见GitHub上issue)。 Brecht Machiels的accepted answer以另一种方式解决了这个问题,直到有一天斯芬克斯能够做到这一点。Python的狮身人面像:从超

描述: 我想用sphinx-apidoc来记录一个Python项目。狮身人面像配置几乎是默认的,我只包括'sphinx.ext.autodoc'

它在一般情况下工作,但派生类不像我期望的那样继承超类的方法文档。

示例: 考虑一个非常简约的Python包,名为project。除了一个空__init__.py它仅包含一个文件(base.py,见下文)

# -*- coding: utf-8 -* 
import abc 


class Superclass(object): 
    """The one to rule them all""" 

    @abc.abstractmethod 
    def give(self, ring): 
     """Give out a ring""" 
     pass 


class Derived(Superclass): 
    """Somebody has to do the work""" 

    def give(self, ring): 
     print("I pass the ring {} to you".format(ring)) 

运行狮身人面像,apidoc(sphinx-apidoc -o apidoc project -f)生成以下文件:

  • apidoc/modules.rst

    project 
    ======= 
    
    .. toctree:: 
        :maxdepth: 4 
    
        project 
    
  • apidoc/project.rst

    project package 
    =============== 
    
    Submodules 
    ---------- 
    
    project.base module 
    ------------------- 
    
    .. automodule:: project.base 
        :members: 
        :undoc-members: 
        :show-inheritance: 
    
    
    Module contents 
    --------------- 
    
    .. automodule:: project 
        :members: 
        :undoc-members: 
        :show-inheritance: 
    

包括apidoc/modules.rst在随后make html默认index.rst产生两个类和它们的方法一个基本的HTML文档。不幸的是,Derived.give的文档字符串为空。

问: 有没有办法告诉狮身人面像在this描述,张贴每个单独的方法拿父母的方法的文档没有装饰的魔力?

回答

3

您可以通过为抽象基类使用元类来自动管理docstrings。以下是这种元类的一个非常基本的实现。它需要扩展以正确处理多个基类和角落案例。

# -*- coding: utf-8 -* 
import abc 


class SuperclassMeta(type): 
    def __new__(mcls, classname, bases, cls_dict): 
     cls = super().__new__(mcls, classname, bases, cls_dict) 
     for name, member in cls_dict.items(): 
      if not getattr(member, '__doc__'): 
       member.__doc__ = getattr(bases[-1], name).__doc__ 
     return cls 


class Superclass(object, metaclass=SuperclassMeta): 
    """The one to rule them all""" 

    @abc.abstractmethod 
    def give(self, ring): 
     """Give out a ring""" 
     pass 


class Derived(Superclass): 
    """Somebody has to do the work""" 

    def give(self, ring): 
     print("I pass the ring {} to you".format(ring)) 

这甚至比有狮身人面像做一个更好的解决办法,因为这也将呼吁派生类help()时工作。

+0

不是我希望的解决方案,但它对我的目的像一个魅力:-) –