问题描述
我有带有对象属性的 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 中记录 foo,self.basepath 和 self.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.