首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >向命名元组添加文档字符串?

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

Stack Overflow用户
提问于 2009-10-22 18:55:53
回答 5查看 15.2K关注 0票数 91

可以以一种简单的方式将文档字符串添加到命名元组中吗?

我试过了

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

但这并不能解决问题。有没有可能用其他方式呢?

EN

回答 5

Stack Overflow用户

发布于 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

票数 74
EN

Stack Overflow用户

发布于 2013-03-28 03:30:28

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

我只想指出,您可以通过直接从类声明中调用namedtuple()来进一步整理它:

from collections import namedtuple

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

Stack Overflow用户

发布于 2018-03-07 21:40:12

在Python 3.6+中,您可以使用:

class Point(NamedTuple):
    """
    A point in 2D space
    """
    x: float
    y: float
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1606436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档