【发布时间】:2016-11-02 06:19:14
【问题描述】:
假设我有这样的课程:
class TestCase(object):
"""Class docstring"""
def meth(self):
"""Method docstring"""
return 1
@property
def prop(self):
"""Property docstring"""
return 2
获取类本身或常规方法的文档字符串对我来说很容易:
tc = TestCase()
print(tc.__doc__)
# Class docstring
print(tc.meth.__doc__)
# Method docstring
但是,这种方法不适用于属性 - 相反,我得到了属性 getter 方法(在本例中为 int)返回的任何对象的 __doc__ 属性:
print(tc.prop.__doc__)
# int(x=0) -> int or long
# int(x, base=10) -> int or long
# ...
getattr(tc, "prop").__doc__ 和 getattr(tc.prop, "__doc__") 也是如此。
我知道 Python 的自省机制能够访问我正在寻找的文档字符串。例如,当我拨打help(tc) 时,我得到:
class TestCase(__builtin__.object)
| Class docstring
|
| Methods defined here:
|
| meth(self)
| Method docstring
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| prop
| Property docstring
help 如何访问tc.prop 的文档字符串?
【问题讨论】:
标签: python properties docstring