我不確定在python2.x上是否有這樣做的好方法。在python3.x,你可以換出__doc__
直接:
$ python3
Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import namedtuple
>>> NT = namedtuple('NT', ['f1', 'f2', 'f3'])
>>> NT.f1.__doc__
'Alias for field number 0'
>>> NT.f1.__doc__ = 'Hello'
不幸的是,python2.x讓你在這一點上的錯誤:
>>> NT.f1.__doc__ = 'Hello World.'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: readonly attribute
在python2.x,你可以得到它重新定義的所有屬性:
>>> from collections import namedtuple
>>> NT = namedtuple('NT', ['f1', 'f2', 'f3'])
>>> class NTWithDoc(NT):
... """docstring."""
... __slots__ =()
... f1 = property(NT.f1.fget, None, None, 'docstring!')
...
>>> help(NTWithDoc)
>>> a = NTWithDoc(1, 2, 3)
>>> a.f1
1
但是,這感覺就像是很多的麻煩去獲得文檔字符串:-)。
請注意,您不需要在該代碼中使用'pass':-) – mgilson
反正您使用的是py 2或py 3 –
請確定您是否使用了[本主題](http://stackoverflow.com/questions/1606436/adding -docstrings-to-namedtuples)覆蓋問題? – alecxe