我怎样才能使Python /狮身人面像文档对象的属性只在__init__声明? [英] How can I make Python/Sphinx document object attributes only declared in __init__?

查看:110
本文介绍了我怎样才能使Python /狮身人面像文档对象的属性只在__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))

如果我现在请使用帮助(美孚)或试图记录在狮身人面像, 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.

我试图寻找一种标准的方式来保证这些动态申报属性可以找到(和preferably docstring'd)解析器,但至今没有运气。有什么建议么?谢谢你。

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

事实上,如果实例变量有一个有用的一成不变的默认值(例如无或空的元组),那么你可以节省只是不设置变量有点内存,如果应该有它的默认值。当然,如果你在谈论一个实例变量,这种做法是行不通的,你可能想要删除(例如,德尔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.

如果您正在使用狮身人面像,并具有autoattribute集,那么这应该得到妥善记录。或者,这取决于你在做什么的情况下,你可以只直接使用狮身人面像 .. PY:属性:指令

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 /狮身人面像文档对象的属性只在__init__声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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