ali*_*i_m 4 python docstring properties
假设我有一个这样的类:
class TestCase(object):
"""Class docstring"""
def meth(self):
"""Method docstring"""
return 1
@property
def prop(self):
"""Property docstring"""
return 2
Run Code Online (Sandbox Code Playgroud)
对于我来说,获取类本身的文档字符串或常规方法很容易:
tc = TestCase()
print(tc.__doc__)
# Class docstring
print(tc.meth.__doc__)
# Method docstring
Run Code Online (Sandbox Code Playgroud)
但是,这种方法不适用于属性 - 而是获取__doc__
属性getter方法返回的任何对象的属性(在本例中int
):
print(tc.prop.__doc__)
# int(x=0) -> int or long
# int(x, base=10) -> int or long
# ...
Run Code Online (Sandbox Code Playgroud)
同样的事情适用于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
Run Code Online (Sandbox Code Playgroud)
如何help
访问docstring tc.prop
?
Mos*_*oye 10
您正尝试__doc__
从实例中访问,该实例将首先尝试评估属性,返回的值可能没有属性__doc__
,或者使用__doc__
返回的类型.
相反,您应该从类本身访问__doc__
for property
:
TestCase.prop.__doc__
Run Code Online (Sandbox Code Playgroud)
因此,要将其扩展到您的类实例,您将使用__class__
获取实例的类,然后获取属性,最后__doc__
:
tc.__class__.prop.__doc__
Run Code Online (Sandbox Code Playgroud)
或者type
用来获取类:
type(tc).prop.__doc__
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1681 次 |
最近记录: |