实例属性错误

Instance attribute error

我正在尝试 .. autoclass:: 具有实例属性的 class:

.. autoclass:: synergine.core.Test.Test
   :members:
   :undoc-members:
   :private-members:

的(在文件 synergine/core/Test.py 中):

class Test:

    def __init__(self):
        #: A foo bar instance attribute !
        self._foo = 'bar'

但是当我 make html sphinx 引发这个错误时:

/home/bux/Projets/synergine/doc/source/Components.rst:143: WARNING: autodoc: failed to import attribute 'Test._foo' from module 'synergine.core.Test'; the following exception was raised:
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/sphinx/util/inspect.py", line 108, in safe_getattr
    return getattr(obj, name, *defargs)
AttributeError: type object 'Test' has no attribute '_foo'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/sphinx/ext/autodoc.py", line 342, in import_object
    obj = self.get_attr(obj, part)
  File "/usr/local/lib/python3.4/dist-packages/sphinx/ext/autodoc.py", line 241, in get_attr
    return safe_getattr(obj, name, *defargs)
  File "/usr/local/lib/python3.4/dist-packages/sphinx/util/inspect.py", line 114, in safe_getattr
    raise AttributeError(name)
AttributeError: _foo

为什么?我需要做什么来记录这个实例属性?

编辑:似乎是错误报告:https://github.com/sphinx-doc/sphinx/issues/956。有什么破解方法吗?

这个问题依然存在! 当我想创建 in-house 开发人员文档时遇到了问题。 因此,我还希望记录 private-protected 变量和 class 常量。

示例:

class Foo(object):
    #: foo is a list for ...
    __foo = []
    __bar = None
    """
    bar stores ...
    """
    # [...]

解决方案:

sphinx.util.inspect中改变函数safe_getattr:

def safe_getattr(obj, name, *defargs):
    """A getattr() that turns all exceptions into AttributeErrors."""
    try:
        if name.startswith("__") and not name.endswith("__"): # <-+ these lines
            obj_name = obj.__name__                           #   | have to be
            if "_%s%s"%(obj_name,name) in obj.__dict__:       #   | added
                name = "_%s%s"%(obj_name,name)                # <-+ 
        return getattr(obj, name, *defargs)
    except Exception as error:
        # this is a catch-all for all the weird things that some modules do
        # with attribute access
        if defargs:
            return defargs[0]
        raise AttributeError(name)     

这将消除错误。 要删除生成文档中受保护的 class 常量的内部名称空间,请更改 sphinx.ext.autodoc:

中的函数 filter_members
def filter_members(self, members, want_all):
    # [...] 
    for (membername, member) in members:
        # [...]
        elif want_all and membername.startswith('_'):
            # ignore members whose name starts with _ by default
            keep = self.options.private_members and \
                        not membername.startswith('_'+namespace) and\  # <- ADD THIS LINE
                        (has_doc or self.options.undoc_members)    
    # [...]