向namedtuples添加docstring?

2024-04-19 07:45:17 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以以简单的方式将文档字符串添加到namedtuple?

我试过了

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

但这并不能切断它。有别的办法吗?


Tags: 字符串infrom文档importdoc方式space
3条回答

在想同样的事情的时候,通过谷歌遇到了这个老问题。

只是想指出,您可以通过从类声明中调用namedtuple()来整理它:

from collections import namedtuple

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

您可以通过在namedtuple返回的值周围创建一个简单的空包装类来实现这一点。我创建的文件的内容(nt.py):

from collections import namedtuple

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

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

然后在Python REPL中:

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

在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

相关问题 更多 >