【问题标题】:How to read the docstring present inside __init__ method of a class?如何读取类的 __init__ 方法中存在的文档字符串?
【发布时间】:2021-04-09 04:45:59
【问题描述】:

我想读取一个类的__init__ 方法中的文档字符串:

class student:
def __init__(self, id, name, tier):
    '''
    :param id: id of the student
    :param name: name of the student
    :param tier: tier of the student
    '''
    self.id = id
    self.name = name
    self.tier = tier


stu = student(7654, 'Sandeep', 12)
print(stu.__doc__)

如果您执行上述脚本,输出将为“无”。

可以读取类的任何其他方法的文档字符串。但是我们如何才能读取类中__init__ 方法的文档字符串呢?

【问题讨论】:

  • 好吧,stu.__doc__ 表示属于该对象的__doc__,或者不属于该类。我们想要的是属于 __init__ 方法的 __doc__stu.__init__(或者student.__init__,直接在类上查找)就是那个方法,所以...

标签: python class docstring


【解决方案1】:

您可能应该将文档字符串向上移动到class student: 行下。如果要获取__init__ 文档字符串,则必须使用stu.__init__.__doc__ 而不是stu.__doc__

【讨论】:

  • 是的,谢谢。我现在可以读取 init 方法中的文档字符串了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
相关资源
最近更新 更多