如何使 Python/Sphinx 文档对象属性仅在 __init__ 中声明? [英] How can I make Python/Sphinx document object attributes only declared in __init__?

查看:30
本文介绍了如何使 Python/Sphinx 文档对象属性仅在 __init__ 中声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有对象属性的 Python 类,这些对象属性仅在运行构造函数时声明,如下所示:

I have Python classes with object attributes which are only declared as part of running the constructor, like so:

class Foo(object):
    def __init__(self, base):
        self.basepath = base

        temp = []
        for run in os.listdir(self.basepath):
            if self.foo(run):
                temp.append(run)
        self.availableruns = tuple(sorted(temp))

如果我现在使用 help(Foo) 或尝试在 Sphinx 中记录 Fooself.basepathself.availableruns 属性未显示.这对我们 API 的用户来说是个问题.

If I now use either help(Foo) or attempt to document Foo in Sphinx, the self.basepath and self.availableruns attributes are not shown. That's a problem for users of our API.

我尝试寻找一种标准方法来确保解析器可以找到(最好是文档字符串)这些动态声明的"属性,但到目前为止还没有运气.有什么建议?谢谢.

I've tried searching for a standard way to ensure that these "dynamically declared" attributes can be found (and preferably docstring'd) by the parser, but no luck so far. Any suggestions? Thanks.

推荐答案

你可以定义一个与实例变量同名的类变量.然后,当您设置它时,该类变量将被实例变量遮蔽.例如:

You could define a class variable with the same name as the instance variable. That class variable will then be shadowed by the instance variable when you set it. E.g:

class Foo(object):
    #: Doc comment for availableruns
    availableruns = ()

    def __init__(self, base):
        ...
        self.availableruns = tuple(sorted(temp))

确实,如果实例变量有一个有用的不可变默认值(例如None或空元组),那么你可以通过不设置变量if应该有它的默认值来节省一点内存.当然,如果您谈论的是您可能想要删除的实例变量(例如,del foo.availableruns),这种方法将不起作用——但我发现这不是一个很常见的情况.

Indeed, if the instance variable has a useful immutable default value (eg None or the empty tuple), then you can save a little memory by just not setting the variable if should have its default value. Of course, this approach won't work if you're talking about an instance variable that you might want to delete (e.g., del foo.availableruns)-- but I find that's not a very common case.

如果您使用的是 sphinx,并且具有自动属性";设置,那么这应该得到适当的记录.或者,根据您正在执行的操作的上下文,您可以直接使用 Sphinx .. py:attribute:: 指令.

If you're using sphinx, and have "autoattribute" set, then this should get documented appropriately. Or, depending on the context of what you're doing, you could just directly use the Sphinx .. py:attribute:: directive.

这篇关于如何使 Python/Sphinx 文档对象属性仅在 __init__ 中声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆