我有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.
更多推荐
发布评论