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

假设我有一个这样的课:

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方法(在本例中为__doc__)返回的任何对象的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的自省机制能够访问我要查找的文档字符串。例如,当我呼叫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

TestCase.prop.__doc__

因此,要将其扩展到您的类实例,可以使用__class__来获取实例的类,然后是属性,最后是__doc__

tc.__class__.prop.__doc__

或使用type获取类:

type(tc).prop.__doc__

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python:检查是否存在维基百科文章 - python

我试图弄清楚如何检查Wikipedia文章是否存在。例如,https://en.wikipedia.org/wiki/Food 存在,但是https://en.wikipedia.org/wiki/Fod 不会,页面只是说:“维基百科没有此名称的文章。”谢谢! 参考方案 >>> import urllib >>> prin…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…