【问题标题】:How to get the doc string attribute of a property?如何获取属性的文档字符串属性?
【发布时间】:2018-11-28 05:57:01
【问题描述】:

我在学习 Python 描述符时遇到了这个例子

class Person(object):
    def __init__(self):
        self._name = ''

    def fget(self):
        print("Getting: %s" % self._name)
        return self._name

    def fset(self, name):
        print("Setting: %s" % name)
        self._name = name.title()

    def fdel(self):
        print("Deleting: %s" %self._name)
        del self._name

    name = property(fget, fset, fdel, "I'm the property.")

它使用property 函数。 article 表示第四个参数是 doc – docstring,

p1 = Person()
p1.name = "Islam"
print(p1.name)
print(p1.name.doc)
del p1.name

但是当我尝试去 doc 时,它会引发

AttributeError: 'str' object has no attribute 'doc'

【问题讨论】:

    标签: python python-3.x properties descriptor


    【解决方案1】:

    首先,由于文档字符串是一个神奇的属性,它应该采用double leading and trailing underscore 形式。所以,它是__doc__ 而不是doc

    其次,当您尝试从类的实例访问__doc__ 时,它将触发实际对象的 doc 属性,在这种情况下是一个字符串。相反,尝试从类对象访问属性:

    In [74]: Person.name.__doc__
    Out[74]: "I'm the property."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 2013-07-04
      • 2021-07-02
      • 1970-01-01
      • 2011-04-12
      相关资源
      最近更新 更多