为命名元组添加文档字符串?

96 投票
11 回答
18518 浏览
提问于 2025-04-15 15:16

有没有简单的方法可以给命名元组加上文档字符串呢?

我试过了

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

但是这样不太行。有没有其他的方法可以做到呢?

11 个回答

68

我在网上搜索的时候碰到了这个老问题,正好也在想同样的事情。

我想提一下,你可以通过在类声明的时候直接调用namedtuple()来让代码更整洁:

from collections import namedtuple

class Point(namedtuple('Point', 'x y')):
    """Here is the docstring."""
75

在Python 3中,不需要额外的包装,因为类型的__doc__属性是可以写的。

from collections import namedtuple

Point = namedtuple('Point', 'x y')
Point.__doc__ = '''\
A 2-dimensional coordinate

x - the abscissa
y - the ordinate'''

这和标准的类定义很像,文档字符串(docstring)是在类头部之后的部分。

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

55

你可以通过创建一个简单的空包装类来处理从 namedtuple 返回的值。下面是我创建的一个文件的内容(nt.py):

from collections import namedtuple

Point_ = namedtuple("Point", ["x", "y"])

class Point(Point_):
    """ A point in 2d space """
    pass

然后在 Python 的交互式环境中:

>>> print nt.Point.__doc__
 A point in 2d space 

或者你也可以这样做:

>>> help(nt.Point)  # which outputs...
Help on class Point in module nt:

class Point(Point)
 |  A point in 2d space
 |  
 |  Method resolution order:
 |      Point
 |      Point
 |      __builtin__.tuple
 |      __builtin__.object
 ...

如果你不想每次都手动这么做,其实可以写一个简单的工厂函数来自动完成这个操作:

def NamedTupleWithDocstring(docstring, *ntargs):
    nt = namedtuple(*ntargs)
    class NT(nt):
        __doc__ = docstring
    return NT

Point3D = NamedTupleWithDocstring("A point in 3d space", "Point3d", ["x", "y", "z"])

p3 = Point3D(1,2,3)

print p3.__doc__

这样输出的结果是:

A point in 3d space

撰写回答