属性文档字符串
考虑一下这段代码:
class MyClass(object):
'''
Keep track of file and its path on disk
'''
def __init__(self):
self.file = None
self.path = None
我想给所有的属性添加文档字符串。比如,我可以这样做(针对文件属性):
class MyClass(object):
...
@property
def file(self):
'''
this is a doc-string for file property
'''
return self._file
@file.setter
def file(self, value):
self._file = value
@file.deleter
def file(self):
del self._file
不过,为每个属性都写获取器、设置器和删除器的方法实在是太麻烦了。实际上,这些方法(就像上面看到的那样)只是做了一些默认的工作。
有没有简单的方法只给属性添加文档字符串呢?
5 个回答
0
不太确定你是不是在找这个,不过如果你在用Sphinx来做文档系统的话,你可以用下面这种语法来添加属性文档:
class MyClass(object):
'''
Keep track of file and its path on disk
'''
def __init__(self):
#: this is doc for file
self.file = None
#: this is the documentation for path
#: on multiple line too.
self.path = None
1
这是DzinX的DocProperty类的修正版:
class DocProperty(object):
def __init__(self, name, doc):
self._name = '_'+name
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self._name)
def __set__(self, obj, value):
setattr(obj, self._name, value)
def __delete__(self, obj):
delattr(obj, self._name)
使用方法:
class SomeClass(object):
p1 = DocProperty('p1', 'some docs')
需要注意的是,使用这个会让你的代码效率降低——每次访问属性的成本会变高。不过我想在某些情况下,能够添加文档说明可能是值得的(特别是如果在你的环境中效率不是主要考虑因素的话)。
2
好吧,你可以自己创建一个描述符,这样就可以添加文档说明,并且按照标准方式实现其他操作:
class DocProperty(object):
def __init__(self, doc=None):
self._values = {}
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
return self._values[obj]
def __set__(self, obj, value):
self._values[obj] = value
def __delete__(self, obj):
del self._values[obj]
然后你可以这样使用它:
class SomeClass(object):
p1 = DocProperty('some docs')
print SomeClass.p1.__doc__
# some docs
c = SomeClass()
c.p1 = 2
print c.p1
# 2
del c.p1
不过我个人觉得这样做有点过于复杂。如果你需要在代码中添加说明,可以在构造函数里使用注释。所有的自动文档生成工具也都支持以某种方式对简单的Python属性进行注释。