gpt4 book ai didi

python - 如何检索 Python 类实例的属性的文档字符串?

转载 作者:行者123 更新时间:2023-12-04 17:07:58 26 4
gpt4 key购买 nike

假设我有这样的类(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com