我如何才能使Python / Sphinx文档对象属性只在

编程入门 行业动态 更新时间:2024-10-27 05:30:14
我如何才能使Python / Sphinx文档对象属性只在__init__中声明?(How can I make Python/Sphinx document object attributes only declared in __init__?)

我有Python类与对象属性,只声明为运行构造函数的一部分,如下所示:

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中记录Foo ,则不会显示self.basepath和self.availableruns属性。 这对我们API的用户来说是个问题。

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

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))

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.

最满意答案

您可以定义一个与实例变量名称相同的类变量。 这个类变量在设置时会被实例变量遮蔽。 例如:

class Foo(object): #: Doc comment for availableruns availableruns = () def __init__(self, base): ... self.availableruns = tuple(sorted(temp))

事实上,如果实例变量具有有用的不可变默认值(例如None或空元组),那么如果应该使用其默认值,则可以通过不设置变量来节省一点内存。 当然,如果你正在讨论一个你可能想删除的实例变量(例如, del foo.availableruns ),这种方法将不起作用 - 但我发现这不是一个很常见的情况。

如果你使用的是狮身人面像,并设置了“自动属性”,那么这应该得到适当的记录。 或者,根据您所做的内容,您可以直接使用Sphinx .. py:attribute:: directive。

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))

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.

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.

更多推荐

本文发布于:2023-07-31 01:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340400.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:只在   能使   属性   对象   文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!