我有一个模块应该具有一个@property
,我通过将类设置为模块来解决了这个问题。 我从这个答案得到了灵感:Lazy module variables--can it be done?
我希望这是可重复且易于使用的,因此我为此制作了一个元类。 这非常好用。
问题在于,在使用Sphinx生成文档时,属性不会被记录。 其他所有内容都按预期记录。 我不知道如何解决这个问题,也许这是Sphinx的问题?
该模块:
import sys
import types
class ClassAsModule(type):
def __new__(cls, name, bases, attrs):
# Make sure the name of the class is the module name.
name = attrs.pop('__module__')
# Create a class.
cls = type.__new__(cls, name, bases, attrs)
# Instantiate the class and register it.
sys.modules[name] = cls = cls(name)
# Update the dict so dir works properly
cls.__dict__.update(attrs)
class TestClass(types.ModuleType):
"""TestClass docstring."""
__metaclass__ = ClassAsModule
@property
def some_property(self):
"""Property docstring."""
pass
def meth():
"""meth doc"""
pass
使用复制粘贴来生成/查看Sphinx文档:
sphinx-apidoc . -o doc --full
sphinx-build doc html
xdg-open html/module.html
最重要的部分是记录类的属性。如果还记录原始模块成员,则会加分。
编辑:应该将该类作为其所在的模块进行文档化。该类是这样使用的,因此在Sphinx中应以这种方式显示。
所需输出示例:
Module Foo
TestClass docstring.
some_property
Property docstring.
meth()
meth doc
编辑2: 我找到了一些可能有助于找到解决方案的东西。当一个常规模块foo
的内容如下:
#: Property of foo
prop = 'test'
Sphinx 对此进行了文档化:
foo.prop = 'test'
Property of foo
如果
prop
是类的属性之一,那么同样适用。 我还没有弄清楚为什么它在我的特殊情况下不起作用。
ModMeta
未定义。你能否提供可运行的代码? - jterracemeth()
中的pass
语句替换为return sys.path
,我会得到这个错误:AttributeError: 'NoneType' object has no attribute 'path'
。如果只返回“Hello”之类的东西,它可以正常工作,但不能访问应该是全局的内容。 - Jacinda