問題描述
我有帶有對象屬性的 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.
這篇關于如何使 Python/Sphinx 文檔對象屬性僅在 __init__ 中聲明?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!