假设我有这样的类(class):
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
但是,这种方法不适用于属性 - 相反,我得到
__doc__
属性 getter 方法返回的任何对象的属性(在本例中为 int
):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 的自省(introspection)机制能够访问我正在寻找的文档字符串。例如,当我调用
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
的文档字符串?
最佳答案
您正在尝试访问 __doc__
从首先尝试的实例,评估属性,返回值可能没有属性__doc__
,或使用 __doc__
返回的类型。
相反,您应该访问 __doc__
对于property
从类(class)本身:
TestCase.prop.__doc__
因此,要将其扩展到您的类实例,您将使用
__class__
获取实例的类,然后是属性,最后是 __doc__
:tc.__class__.prop.__doc__
或使用
type
获取类(class):type(tc).prop.__doc__
关于python - 如何检索 Python 类实例的属性的文档字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38118264/