从父 class 到子 class 函数的文档字符串

Doc string from parent class to children class functions

我有一个带有 djangorestframework==3.9.4django-rest-swagger==2.2.0Django==2.2.3 应用程序。我想为我的 api 端点提供单一的真实来源(用于数据验证和 api-docs)。我有一个看起来像这样的 JSON

{
    "get": {
        "query_param1" : {
            "type": "string",
            "required": "false",
            "message": "what does it do/what is it for?"
        },
        "query_param2" : {...},
        "responseMessages": {
            "code: 401": "Not authenticated",
            "code: 403": "Insufficient rights to call this procedure"
        }
    },
    "delete": {
        "query_param1" : {...},
        "query_param2" : {...},
        "responseMessages": {...},
    },
    "put": {...},
    "post": {...},
}

我从中创建了一个 json 模式,验证工作正常。

这个 json 被转换为一个 yaml 字符串,供 django-rest-swagger 使用。它如何使用 yaml,你需要将 yaml 放在文档字符串中。但我不想去为每一件事写同样的东西。会有很多端点,为所有这些端点编写相同的东西感觉不对。

所以我想如果我创建一个基础 class 并将 json 发送到该基础 class,它可以为我创建所有文档字符串,使用 json 并将其动态地放入所需的函数中。我现在遇到一个拦截器,它说。

AttributeError: 'method' 对象的属性 '__ doc __' 不可写

这就是我的 class 的样子

class Parent:
  def __init__(self):
    schema = json.load(schema_path)
    self.get.__doc__ = convertToYaml(schema['get'])
    **ERROR HERE: AttributeError: attribute '__doc__' of 'method' objects is not writable**


class Child(Parent)
  def get(self):
    JsonResponse({message: "Hi! I work fine" })

TLDR:

获取错误: AttributeError: attribute __ doc __ of method objects is not writable

问题:如何从父 class 更改子 class 函数的文档字符串?

您可以在父级的 __new__ 方法中定义它。

这是一个简单的例子,说明如何覆盖它。

class Parent(object):
    """ This is the Parent"""
    def __new__(cls):
        cls.__init__.__doc__ = cls.__bases__[0].__doc__
        return object.__new__(cls)

    def __init__(self):
        print('hello')


class Child(Parent):
    """ This is the Child """
    def __init__(self):
        super().__init__()

test = Child()

print(test.__init__.__doc__)

在你的例子中是这样的:

class Parent(object):
    def __new__(cls):
        schema = json.load(schema_path)
        cls.get.__doc__ = convertToYaml(schema['get'])
        return object.__new__(cls)