我创建了一系列节点,每个节点都有一组与之关联的属性对象.使用每个属性的描述和名称初始化属性对象.我希望这些属性及其描述能够在我的sphinx文档中显示,而不必在两个地方维护名称/描述,一次在类的doc字符串中,一次在属性的初始化中.
要说明问题,请考虑以下代码:
class Foo(object):
"""My doc string
"""
@classmethod
def default_attributes(cls):
return {'foo':'description of foo attribute',
'bar':'description of bar attribute'}
@classmethod
def attributes_string(cls):
attributes = cls.default_attributes()
result = '\nDefault Attributes:\n'
for key, value in attributes.iteritems():
result += '%s: %s\n' % (key, value)
return result
print Foo.__doc__
Run Code Online (Sandbox Code Playgroud)
我希望Foo.attributes_string的结果显示在Foo的doc字符串中,以便我得到这个:
My doc string
Default Attributes:
foo: description of foo attribute
bar: description of bar attribute
Run Code Online (Sandbox Code Playgroud)
首先我想"嘿,这很简单!我只是设置一个类装饰器!":
def my_decorator(cls):
doc = getattr(cls, '__doc__', '')
doc += cls.attributes_string()
cls.__doc__ = doc
return cls …Run Code Online (Sandbox Code Playgroud)