2013-04-09 101 views
12

具體的特殊方法,我有一堆它們使用「特殊方法」類:包括在獅身人面像

class Foo(object): 
    "Foo docstring" 

    attr1 = "Attribute!" #: first attribute 
    attr2 = "Another Attribute!" #: second attribute 

    def __init__(self): 
     self.x = 12 

    def say_hello(self): 
     """ 
     say_hello(self) -> None 

     Issue a friendly greeting. 
     """ 
     print "Hello! x is {0}".format(self.x) 

    def __contains__(self,other): 
     """Implement ``other in self``""" 
     return other == self.x 

現在我想生成該使用獅身人面像和車博士HTML文檔。我如何告訴獅身人面像文件__contains__?我嘗試添加

autodoc_default_flags = ['members', 'undoc-members', 'special-members'] 

conf.py,但也包括__dict__這是我絕對不想。

目前,myproject.rst文件模樣的相關部分:

.. automodule:: myproject.foomodule 
    :members: 
    :undoc-members: 
    :show-inheritance: 

編輯加入

.. automodule:: myproject.foomodule 
    :members: 
    :undoc-members: 
    :show-inheritance: 

.. automethod:: myproject.foomodule.Foo.__contains__ 

確實增加了該方法的文檔,但在一個單獨的部分 - 不爲部分Foo類文檔。

+0

OTTOMH - 我相信你必須要明確,使用'.. automethod :: __contains__',因爲我不相信'特殊members'接受任何形式的濾波參數 – 2013-04-09 13:46:29

+0

問題中的示例並不完全顯示記錄此方法的引人注目的情況。如果它只是告訴你一個對象是否是一個集合的成員,那麼記錄'__contains__'沒有意義。這是[已經在Python中記錄](http://docs.python.org/3/reference/datamodel.html#object.__contains__)。您可能會在文檔字符串中提到支持'in'運算符的類。 – 2013-04-09 13:55:22

+0

@JonClements - 看起來很接近。我在上面的'..automethod'東西之後添加了一個'.. automethod :: myproject.foomodule.Foo .__ contains__'',它添加了文檔,但是它與文檔分開記錄。 – mgilson 2013-04-09 13:55:59

回答

3

我目前對此解決方案並非百分百激動,所以我希望有人能夠一起改進它。不過,我已經解決了這個問題的辦法是做到以下幾點:

.. automodule:: myproject.foomodule 
    :members: 
    :undoc-members: 
    :show-inheritance: 

    .. autoclass:: myproject.foomodule.Foo 
     :exclude-members: attr1,attr2 

     .. autoattribute:: myproject.foomodule.Foo.attr1 

     .. autoattribute:: myproject.foomodule.Foo.attr2 

     .. automethod:: myproject.foomodule.Foo.__contains__ 

在這裏,我真的需要告訴autodoc避免(自動)記錄類屬性,然後我需要將它們添加回明確。原因是顯然當你明確地嵌套命令,explicit ones come first。如果我只明確地說要添加__contains__,那麼它顯示在我不喜歡的屬性之前。

+0

http://stackoverflow.com/a/21449475/832230有幫助嗎? – 2014-01-30 06:42:24

11

您可以添加:

:special-members: 
:exclude-members: __dict__,__weakref__ 

.rst文件,以示特殊的成員,除了__dict____weakref__

7

什麼工作對我來說是增加了」 .. automethod :: 方法名

指令在類的文檔字符串中,而不是在.rst文件中執行。

所以,你可以改變「富文檔字符串」到

""" 
Foo docstring 

.. automethod:: __contains__ 
""" 
+0

很高興知道。我(不幸)不再能夠使用獅身人面像 - 所以我無法測試這一點。如果我有機會,我一定會放棄它。 – mgilson 2014-02-28 06:05:02

4

special-members選項現在接受參數(這是獅身人面像1.2的新特性)。

所以這應該工作:

.. automodule:: myproject.foomodule 
    :members: 
    :undoc-members: 
    :special-members: __contains__ 
    :show-inheritance: