可以以一种简单的方式将文档字符串添加到命名元组中吗?
我试过了
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
"""
A point in 2D space
"""
# Yet another test
"""
A(nother) point in 2D space
"""
Point2 = namedtuple("Point2", ["x", "y"])
print Point.__doc__ # -> "Point(x, y)"
print Point2.__doc__ # -> "Point2(x, y)"
但这并不能解决问题。有没有可能用其他方式呢?
发布于 2013-12-05 07:43:06
在Python3中,不需要包装器,因为类型的__doc__
属性是可写的。
from collections import namedtuple
Point = namedtuple('Point', 'x y')
Point.__doc__ = '''\
A 2-dimensional coordinate
x - the abscissa
y - the ordinate'''
这非常类似于标准的类定义,其中文档字符串紧跟在头部之后。
class Point():
'''A 2-dimensional coordinate
x - the abscissa
y - the ordinate'''
<class code>
这在Python 2中不起作用。
AttributeError: attribute '__doc__' of 'type' objects is not writable
。
发布于 2013-03-28 03:30:28
在想着同样的事情时,我通过谷歌遇到了这个老问题。
我只想指出,您可以通过直接从类声明中调用namedtuple()来进一步整理它:
from collections import namedtuple
class Point(namedtuple('Point', 'x y')):
"""Here is the docstring."""
发布于 2018-03-07 21:40:12
在Python 3.6+中,您可以使用:
class Point(NamedTuple):
"""
A point in 2D space
"""
x: float
y: float
https://stackoverflow.com/questions/1606436
复制相似问题