Python如何从另一个类“借用”docstring?

2024-04-26 00:48:42 发布

您现在位置:Python中文网/ 问答频道 /正文

背景

我使用django rest swagger来显示API文档,swagger的官方方法是从视图中使用docstring。你知道吗

目的

作为docstring的许多文档都是在Model类中完成的,因此我想将docstring从Model类“借用”到APIModelView类中,而不需要实际复制docstring。你知道吗

例如

class Model(models.Model):
  """
  Very comprehensive docstring...
  """

  field_1 = ...
  field_2 = ...


class APIModelView(ModelView):
  """
  <borrow from the model class>
  """
  model = Model

扩展

@Martijn Pieters的答案在类级docstring上运行良好

我刚刚意识到swagger实际上使用了实例方法docstring,例如

class APIModelView(ModelView):
      def list(self, request, *args, **kwargs):
          __doc__ = Model.__doc__
          ...

但上面说的行不通。。。你知道吗


Tags: django方法文档restapifielddocmodel
1条回答
网友
1楼 · 发布于 2024-04-26 00:48:42

创建类时可以设置__doc__属性;只需将其作为原始模型的副本:

class APIModelView(ModelView):
    __doc__ = Model.__doc__
    model = Model

如果类上没有实际的docstring,则保留任何已经存在的__doc__属性。你知道吗

相关问题 更多 >